如何在Mongo中选择数组的一部分并进行过滤?

时间:2018-03-13 14:45:53

标签: mongodb mongodb-query

我在Mongo中有一个包含如下文档的集合:

{
    name: "Bob",
    destinations:
    [
        {
            city: "Dallas",
            state: "Texas",
            isBusiness: "true",
        }, {
            city: "San Diego",
            state: "California",
            isBusiness: "true",
        }   
    ]
},
{
    name: "Sue",
    destinations:
    [
        {
            city: "Las Vegas",
            state: "Nevada",
            isBusiness: "false",
        }, {
            city: "Sacramento",
            state: "California",
            isBusiness: "true",
        }   
    ]
}

我想查询此收藏集,以便我收到每个人的name以及加利福尼亚州内每个目的地的city,但不会收到isBusiness值被忽略了。

查询结果应为:

[
    {
        name: "Bob",
        city: "San Diago",
    },
    {
        name: "Sue",
        city: "Sacramento"
    }
]

这个例子有点人为,但我该怎么做?

3 个答案:

答案 0 :(得分:1)

相当基本的聚合,不知道该解释一下:

db.collection.aggregate([
    {$unwind: "$destinations"},
    {$match: {"destinations.state":"California"}},
    {$project: {_id:0, name: 1, city: "$destinations.city"}}
])

文档:

答案 1 :(得分:0)

db.collectionName.find({"destinations.state":"California"},{name:1,"destinations.city":1})

答案 2 :(得分:0)

MongoDB的$ elemMatch运算符用于对元素数组应用过滤器。

根据上述问题的描述,请尝试在MongoDB shell中找到执行以下查找操作。

db.collection.find({
    destinations: {
        $elemMatch: {
            state: "California"
        }
    }
}, {
    'destinations.$': 1,
    name: 1,
    _id: 0
})