grunci
grunci

Reputation: 89

MongoDB Aggregation - Merge arrays of an object

I would like to get the union of all the arrays in an object in MongoDB 3.4 using the aggregation framework:

This is the input:

{ 
  _id: "001",
  name: "something",
  important_part: {
    foo: [1,2,3],
    bar: [4,5],
    x: [6,7]
  }
}

This should be the output:

{ 
  _id: "001",
  name: "something",
  merged_arrays: [1,2,3,4,5,6,7]
}

The tricky part is, that the fields in the important_part object is dynamic, and I don't think the $setUnion operator can be used, as it needs the exact list of array fields.

Could someone please help me?

Thx in advance

Upvotes: 1

Views: 4863

Answers (1)

s7vr
s7vr

Reputation: 75984

You can use below aggregation in 3.4.

$objectToArray to transform object into array of key value pairs and $reduce to $concatArrays.

db.col.aggregate({
  "$addFields":{
    "merged_arrays":{
      "$reduce":{
        "input":{"$objectToArray":"$important_part"},
        "initialValue":[],
        "in":{"$concatArrays":["$$value", "$$this.v"]}
      }
    }
  }
})

Upvotes: 3

Related Questions