【问题标题】:mongodb - merge two objects based on condition fieldmongodb - 根据条件字段合并两个对象
【发布时间】:2020-10-18 22:13:14
【问题描述】:

假设我们有以下来自聚合管道的文档:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "description": "description for item 1",
    "item_code": "00001"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "description": "description for item 2",
    "item_code": "00002"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "description": "description for item 3",
    "item_code": "00003"
  },
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "extrafield": "extra field for item 2",
    "item_code": "00002"
  }
]

如何将具有相同item_code 的文档合并为一个,同时保留所有属性? 期望的结果:

[
  {
    "description": "description for item 1",
    "item_code": "00001"
  },
  {
    "description": "description for item 2",
    "extrafield": "extra field for item 2",
    "item_code": "00002"
  },
  {
    "description": "description for item 3",
    "item_code": "00003"
  }
]

我尝试了不同的$group 模式但没有成功:(

Here's mongodb playground

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    你可以试试,

    • $group by item_code,使用$mergeObjects$$ROOT 合并对象
    • $replaceWith 将根对象替换为根
    db.collection.aggregate([
      {
        $group: {
          _id: "$item_code",
          root: { $mergeObjects: "$$ROOT" }
        }
      },
      { $replaceWith: "$root" }
    ])
    

    Playground

    【讨论】:

    • 谢谢@turivishal。我正朝着那个方向前进,但是使用 $push: "$$ROOT" (而不是 $mergeObjects: "$$ROOT") 没有成功。老实说,我无法弄清楚为什么您的解决方案有效而我的解决方案无效:)
    • group by _id 表示,group 拥有所有分组的对象,$mergeObjects 将对象合并到单个对象中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多