1

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

2

1 Answer 1

3

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"]}
      }
    }
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.