简体   繁体   中英

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

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"]}
      }
    }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM