我需要帮助在嵌套在object中的数组中通过id查找对象

时间:2015-07-18 21:38:48

标签: mongodb

school object :{
    "id":"school1"
    "adress":"aaaaa" 
    "studentInfo":{
        "details" : [ 
            {
                "class" : "a",
                "studentId" : "dan",
                "subject" : "math",

            },
            {
                "class" : "b",
                "studentId" : "ron",
                "subject" : "math",

            }
        ]
    }
}

我有问题从详细信息数组中获取特定对象。 我想要的结果是通过studentId找到:

{
    "class" : "a",
    "studentId" : "dan",
    "subject" : "math",
}

我试过了:

db.getCollection('schools').find(
    {'name':'school1'},
    {'studentInfo.details':{$elemMatch:{'studentId':'dan'} } }
)

提前致谢

2 个答案:

答案 0 :(得分:0)

db.findOne({ studentId: "dan" })

答案 1 :(得分:0)

这是一种方法:下面是shell命令:

db.schools.find({"id" : "school1", "studentInfo.details.studentId" :"dan"}, {"studentInfo.details.$" : 1})