kagmole
kagmole

Reputation: 2165

Group 2 objects into 1 object and merge the keys

I am trying to group 2 objects in my MongoDB documents into a single object with the keys merged. What I have is:

{
  "_id": ObjectId("..."),
  "object_a": { "keyA": 1, "keyB": "valueB" }
  "object_b": { "keyC": 2 }
}

And what I try to get is the following:

{
  "_id": ObjectId("..."),
  "object_a": { "keyA": 1, "keyB": "valueB", "keyC": 2 }
}

I tried with the $addFields operator but this will nest object_b inside object_a, not merge the keys.

{
  "$addFields":
  {
    "object_a": "$object_b"
  }
}

In other words, I am looking for a $setUnion but for objects.

Upvotes: 2

Views: 10948

Answers (2)

Zorji
Zorji

Reputation: 1072

Here is an improved version for Mongo 3.4.4+ that handles null values. It is based on the solution provided by @Veeram

function $mergeObjects(...items) {
  return {
    $arrayToObject: {
      $setUnion: items.map(_ => (
        {$filter: {input: {$objectToArray: _}, cond: {$ne: ["$$this.v", null]}}}
      ))
    }
  }
}

Upvotes: 0

s7vr
s7vr

Reputation: 75994

You can use $mergeObjects in 3.6.

{"$addFields":{"object_a": {"$mergeObjects": ["$object_a", "$object_b"]}}} 

For 3.4 you can use $arrayToObject and $objectToArray to merge keys.

{"$addFields":{"object_a": { "$arrayToObject": {"$setUnion": [{"$objectToArray": "$object_a"},{"$objectToArray": "$object_b"}]}}}}

Upvotes: 4

Related Questions