我在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"
}
]
这个例子有点人为,但我该怎么做?
答案 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
})