【问题标题】:How to get all matching items from a array of objects in MongoDB? [duplicate]如何从 MongoDB 中的对象数组中获取所有匹配项? [复制]
【发布时间】:2017-06-13 22:31:47
【问题描述】:

我有一个如下所示的 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
})

是否有可能获得所有匹配的项目?我在这里缺少什么?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用聚合:

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

    【讨论】:

    • 嗯,我可以使用聚合,但我实际上正在寻找简单的东西。虽然我不确定是否有其他方法可以做到这一点。谢谢。
    • $elemMatch projection returns only the first matching element,所以你必须使用聚合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 2017-02-11
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多