MongoDB:从没有父文档的嵌入文档中检索值

MongoDB: Retrieve value from embedded document, without parent document

现在我有当前文件:

[
  {
    "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 上有一些查询条件(这里 qty = 5),格式如下(没有父文档 'people'包括):

[{"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});

但是这个 returns 父文档,即给了我这个:

{ name: 'John',
  people: { id: '1', qty: '5'} }

知道如何查询以获得所需的输出吗?

查询

  • uwind people 让每个成员在不同的文档中
  • 过滤器只获取 qty=5
  • 取消嵌套并获得所需结构的项目

*如果您在 people.qty 上有一个多键索引,您也可以将其添加为第一阶段
{"$match": {"people.qty": "5"}}

Test code here

aggregate(
[{"$unwind": {"path": "$people"}}, 
 {"$match": {"people.qty": "5"}},
 {"$project": 
   {"_id": 0, "name": 1, "id": "$people.id", "qty": "$people.qty"}}])