如何使用聚合在 MongoDB 中的文档根目录中输出数组对象?

How to output object of an array in the root of the document in MongoDB using aggregation?

我有这个文件:

{"_id":"1", "elem":"ok",
   "arrayOfObjects":[
                     {"type":"k","fieldx":"lol"},
                     {"type":"SndObject","fieldy":"foo"},
                     {"type":"Object1","fieldx":"bob"}
                    ]
}

具有此输出的聚合是什么:

{"_id":"1", "elem":"ok",
"Object1":[
          {"type":"Object1","fieldx":"lol"},
          {"type":"Object1","fieldx":"bob"}
          ],
 "SndObject":[{"type":"SndObject","fieldy":"foo"}]
}

我找到了出路,但它需要我知道我拥有的所有类型:

{ 
  "$addFields" : { 
    "Object1" : { 
      "$filter": { 
        "input": "$arrayOfObjects", 
        "as": "types", 
        "cond": { 
          "$and": [{ "$eq": [ "$$types.type", "Object1" ] }] 
        }
      } 
    }
  }
}

如果我可以遍历我的 arrayOfObjects 并在不知道类型的情况下获得相同的结果,那将是最好的。

可能会有比这更简单的选择,

  • $unwind解构arrayOfObjects数组
  • $group by _id, type and elem,构造arrayOfObjects
  • 的数组
  • $arrayToObject 将 k 和 v 从数组转换为对象
  • $group by _id 并合并 root
  • 中的对象
db.collection.aggregate([
  { $unwind: "$arrayOfObjects" },
  {
    $group: {
      _id: {
        type: "$arrayOfObjects.type",
        _id: "$_id"
      },
      elem: { $first: "$elem" },
      arrayOfObjects: { $push: "$arrayOfObjects" }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      elem: { $first: "$elem" },
      arrayOfObjects: { 
        $mergeObjects: {
          $arrayToObject: [[
              {
                k: "$_id.type",
                v: "$arrayOfObjects"
              }
          ]]
        }
      }
    }
  }
])

Playground