现在我有了当前的文档:
[
{
"name": "John",
"state": "CA",
"people": [
{
"id": "1",
"qty": "5",
"type": "3"
},
{
"id": "4",
"qty": "5",
"type": "6"
}
]
},
{
"name": "Katie",
"state": "NY",
"people": [
{
"id": "434",
"qty": "5",
"type": "63"
},
{
"id": "34",
"qty": "6",
"type": "21"
}
]
}
]
我想要的是一个查询,它只检索名称、id和数量,并在id上设置一些查询条件(这里的数量=5(,格式如下(不包括父文档"人员"(:
[{"name": "John", "id": "1", "qty": "5",},
{"name": "John", "id": "4", "qty": "5",},
{"name": "Katie", "id": "434", "qty": "5",}]
我有这个问题:
db.collection.find( { "qty": "5"}, { "name": 1,"people.id": 1, "people.qty": 1});
但这会返回父文档,即给我这个:
{ name: 'John',
people: { id: '1', qty: '5'} }
有什么想法吗?如何查询以便获得所需的输出?
查询
- u查找人员以获取不同文档中的每个成员
- 筛选以仅获取
qty=5
- 项目以取消嵌套并获得所需的结构
*如果您在people.qty
上有一个多密钥索引,您也可以将其添加为第一阶段{"$match": {"people.qty": "5"}}
此处测试代码
aggregate(
[{"$unwind": {"path": "$people"}},
{"$match": {"people.qty": "5"}},
{"$project":
{"_id": 0, "name": 1, "id": "$people.id", "qty": "$people.qty"}}])