如何从MongoDB中的对象数组中获取所有匹配项?

如何从MongoDB中的对象数组中获取所有匹配项?,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我有一个mongo文档,如下所示 { "_id" : ObjectId("588adde40fcbbbc341b34e1c"), "title" : "Fifa world cup", "tags" : [ { "name" : "Football", "type" : "Sports" }, { "name" : "World cup",

我有一个mongo文档,如下所示

{
    "_id" : ObjectId("588adde40fcbbbc341b34e1c"),
    "title" : "Fifa world cup",
    "tags" : [ 
        {
            "name" : "Football",
            "type" : "Sports"
        }, 
        {
            "name" : "World cup",
            "type" : "Sports"
        }, 
        {
            "name" : "Fifa",
            "type" : "Manager"
        }
    ]
}
我编写了下面的查询来获取所有类型为
Sports
的标签,但是我只得到了1项而不是2项

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

有可能得到所有匹配的项目吗?我这里缺少什么?

您可以使用聚合:

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

嗯,我可以使用聚合,但我实际上在寻找一些简单的东西。虽然我不确定是否有其他方法可以做到这一点。谢谢。
$elemMatch
投影,因此必须使用聚合。