How to get all matching items from a array of objects in MongoDB? [duplicate]

戏子无情 提交于 2019-12-11 06:22:59

问题


I have a mongo document like below

{
    "_id" : ObjectId("588adde40fcbbbc341b34e1c"),
    "title" : "Fifa world cup",
    "tags" : [ 
        {
            "name" : "Football",
            "type" : "Sports"
        }, 
        {
            "name" : "World cup",
            "type" : "Sports"
        }, 
        {
            "name" : "Fifa",
            "type" : "Manager"
        }
    ]
}

I wrote the below query to get all the tags with type Sports but I am only getting 1 item instead of 2

db.collection.find(
{ 
    tags: 
    { 
        $elemMatch: 
        { 
                type: "Sports" 
        }
    }
},
{
    "tags.$" : 1
})

Is it possible to get all the matching items? What I am missing here?


回答1:


You can use aggregation:

db.collection.aggregate([
{
    $unwind : "$tags"
},
{
    $match : {
        "tags.type" : "Sports"
    }
},
{
    $group : {
        _id : "$_id",
        tags : {$addToSet : "$tags"}
    }
}
])


来源:https://stackoverflow.com/questions/41907588/how-to-get-all-matching-items-from-a-array-of-objects-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!