MongoDB 聚合:展开并将根保留为单独的文档

MongoDB aggregate: unwind and keep roots as seperate documents

我想从这个文档开始:

{
  _id: 1,
  property: "a",
  children: [
    { _id: 2, property: "b" },
    { _id: 3, property: "c" }
  ]
}

对此:

{ _id: 1, property: "a" }
{ _id: 2, property: "b" }
{ _id: 3, property: "c" }

使用 MongoDB 聚合函数。我还没有找到合适的东西。 $unwind 最接近,但并没有完全达到预期的结果。

您可以使用聚合框架来完成:

  • $concatArrays - 从父对象添加新的 属性 到 children 数组
  • $project - 仅 return children array
  • $unwind - 将 children 数组展开为多个文档
  • $replaceRoot - 将文档的根替换为 children 属性
db.collection.aggregate([
  {
    "$project": {
      "_id": 0,
      "children": {
        "$concatArrays": [
          "$children",
          [
            {
              "_id": "$_id",
              "property": "$property"
            }
          ]
        ]
      }
    }
  },
  {
    "$unwind": "$children"
  },
  {
    "$replaceRoot": {
      "newRoot": "$children"
    }
  }
])

Working example