mongodb - merge two objects based on condition field

Viewed 1091

Suppose we have the following documents resulting from an aggregation pipeline:

[
  {
    "_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"
  }
]

How can I merge documents with same item_code into one, keeping all properties? Desired result:

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

I've tried different $group pattern without success :(

Here's mongodb playground

1 Answers

You can try,

  • $group by item_code, merge objects using $mergeObjects with $$ROOT
  • $replaceWith to replace root object to root
db.collection.aggregate([
  {
    $group: {
      _id: "$item_code",
      root: { $mergeObjects: "$$ROOT" }
    }
  },
  { $replaceWith: "$root" }
])

Playground

Related