查询嵌套JSON文档中的多个元素

时间:2014-12-08 10:12:10

标签: json mongodb mongodb-query

我在MongoDB中有以下示例数据:

{
    "_id" : ObjectId("54833e93ade1a1521a2a2fe8"),
    "fname" : "yumi",
    "mname" : "sakura",
    "lname" : "kirisaki",
    "consultations" : [
        {
            "medications" : [
                "paracetamol",
                "ibuprofen",
                "carbocisteine"
            ],
            "diagnosis" : [
                "sore throat",
                "fever",
                "cough"
            ],
            "date" : ISODate("2014-12-01T16:00:00Z")
        },
        {
            "medications" : [
                "paracetamol",
                "carbocisteine",
                "afrin"
            ],
            "diagnosis" : [
                "cough",
                "colds",
                "fever"
            ],
            "date" : ISODate("2014-12-11T16:00:00Z")
        }
    ]
}
{
    "_id" : ObjectId("54833e93ade1a1521a2a2fe9"),
    "fname" : "james",
    "mname" : "legaspi",
    "lname" : "reyes",
    "consultations" : [
        {
            "medications" : [
                "zanamivir",
                "ibuprofen",
                "paracetamol"
            ],
            "diagnosis" : [
                "influenza",
                "body aches",
                "headache"
            ],
            "date" : ISODate("2014-10-22T16:00:00Z")
        },
        {
            "medications" : [
                "carbocisteine",
                "albuterol",
                "ibuprofen"
            ],
            "diagnosis" : [
                "asthma",
                "cough",
                "headache"
            ],
            "date" : ISODate("2014-11-13T16:00:00Z")
        }
    ]
}

我正在尝试使用 zanamiviribuprofen以及cough 查询患者:

db.patient.find({
    $and:
        [
            {"consultations.medications":["zanamivir", "ibuprofen"]},
            {"consultations.diagnosis":"cough"}
        ]
}).pretty()

因此,在简短的样本数据中,我希望将james返回,因为他是唯一一个zanamivir药物的人。

当我在cmd中输入上述查询时,没有发生任何事情。它只是进入下一行(没有语法错误等)

我该如何处理查询?

2 个答案:

答案 0 :(得分:2)

非常简单,它只是查询的第一部分。

db.patient.find({
    $and:[
         {"consultations.medications":["zanamivir", "ibuprofen"]}, 
         {"consultations.diagnosis":"cough"}]})

要求Mongodb找到针对[" zanamivir","布洛芬"]的咨询,要求它找到药物等于[' zanamivir' ,'布洛芬']。

如果您想找到使用扎那米韦和布洛芬加药的人,您需要调整查询:

db.patient.find({
    $and:[
         {"consultations.medications":"zanamivir"}, 
         {"consultations.medications":"ibuprofen"}, 
         {"consultations.diagnosis":"cough"}]})

享受!

答案 1 :(得分:2)

您需要使用$all运算符。

db.patient.find({ 
    "consultations.medications": { "$all" : [ "zanamivir", "ibuprofen" ]},
    "consultations.diagnosis": "cough"
})