MongoDB - 仅从Object返回匹配的数组

时间:2016-02-15 11:07:26

标签: mongodb

我在一个集合中有以下文件:

{
    "_id" : 101,
    "students" : [ 
        {
            "name" : "john",            
            "age" : 10,
            "city":'CA'
        },
        {
            "name" : "danial",            
            "age" : 15,
            "city":'KA'
        }
    ]
}

{
    "_id" : 102,
    "students" : [ 
        {
            "name" : "adam",            
            "age" : 20,
            "city":'NY'
        },
        {
            "name" : "johnson",            
            "age" : 12,
            "city":'CA'
        }
    ]
}

我发出以下疑问:

db.data.find({'students.city':'CA'})

这让我和#34;学生"来自两个文档的对象,因为一个实例匹配过滤器(" city&#34 ;;' CA')。

但是,我希望只在结果中获得匹配的数组。也就是说,我想要以下结果:

{
    "_id" : 101,
    "students" : [ 
        {
            "name" : "john",            
            "age" : 10,
            "city":'CA'
        }
    ]
}

{
    "_id" : 102,
    "students" : [        
        {
            "name" : "johnson",            
            "age" : 12,
            "city":'CA'
        }
    ]
}

请帮忙。

2 个答案:

答案 0 :(得分:3)

您需要在投影中使用 $elemMatch

> db.data.find({'students.city':'CA'},{ students:{ $elemMatch:{'city':'CA'} }})
{ "_id" : 101, "students" : [ { "name" : "john", "age" : 10, "city" : "CA" } ] }
{ "_id" : 102, "students" : [ { "name" : "johnson", "age" : 12, "city" : "CA" } ] }
顺便说一下:我强烈建议你阅读Open letter to students with homework problems

答案 1 :(得分:-1)

我认为你应该使用聚合操作。

这里有文档: https://docs.mongodb.org/manual/aggregation/

还有一个类似的问题: Retrieve only the queried element in an object array in MongoDB collection