如何从MongoDB中的对象数组中获取所有匹配项? [英] How to get all matching items from a array of objects in MongoDB?

查看:557
本文介绍了如何从MongoDB中的对象数组中获取所有匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像下面的mongo文档

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"
        }
    ]
}

我写了下面的查询来获取所有类型为Sports的标签,但我只得到了1个项目,而不是2个.

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?

推荐答案

您可以使用聚合:

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

这篇关于如何从MongoDB中的对象数组中获取所有匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆