MongoDB 合并数组中的数组元素

MongoDB merge Array Elements inside an Array

我有一个collection。

{ 
    "_id" : "410a7cb2-7ee1-4e7a-9fb7-fa651fcaa4e5", 
    "reqHistoryEvents" : [
        {
            "reqHistoryMsg" : "abcd", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:18:30.850+0000"), 
           
        }, 
        {
            "reqHistoryMsg" : "EFGH ", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716+0000"), 
          
        }, 
        {
            "reqHistoryMsg" : "IJKL", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716+0000"), 
        }
    ]
}

我想把它转换成这个:::::

{ 
    "_id" : "410a7cb2-7ee1-4e7a-9fb7-fa651fcaa4e5", 
    "reqHistoryEvents" : [
        {
            "reqHistoryMsg" : "abcd", 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:18:30.850+0000"), 
           
        }, 
        {
            "reqHistoryMsg" : ["EFGH ","IJKL"], 
            "reqHistoryCreatedAt" : ISODate("2022-04-27T08:22:12.716+0000"), 
          
        }
    ]
}

基本上会以创建时间戳为准。如果我们有相同的 reqHistoryCreatedAt,我们需要合并 reqHistoryMsg。

我无法编写 mongo 查询。有帮助吗?

  1. $unwind - 解构 reqHistoryEvents 数组字段。
  2. $group - 按 _idreqHistoryEvents.reqHistoryCreatedAt 字段分组。将 reqHistoryMsg 添加到数组中。
  3. $group - 按 _id 字段分组并形成 reqHistoryEvents 数组。
db.collection.aggregate([
  {
    $unwind: "$reqHistoryEvents"
  },
  {
    $group: {
      _id: {
        _id: "$_id",
        reqHistoryCreatedAt: "$reqHistoryEvents.reqHistoryCreatedAt"
      },
      reqHistoryMsg: {
        $push: "$reqHistoryEvents.reqHistoryMsg"
      }
    }
  },
  {
    $group: {
      _id: "$_id._id",
      reqHistoryEvents: {
        $push: {
          reqHistoryMsg: "$reqHistoryMsg",
          reqHistoryCreatedAt: "$_id.reqHistoryCreatedAt"
        }
      }
    }
  }
])

Sample Mongo Playground