mongodb - How can I merge two field arrays in many documents into a single set? -
i have mongodb collection data looks this:
{ "_id" : "1", "array1" : [ "1", "2" ] }, { "_id" : "2", "array2" : [ "1", "3" ] }, { "_id" : "3", "array1" : [ ] }, { "_id" : "4", "array2" : [ ] }, { "_id" : "5" }, { "_id" : "6", "array1" : [ "3", "4" ], "array2" : [ "5" ] } i find query returns unique array values in single array so:
{"_id":"theid", "result":["1", "2", "3", "4", "5"]} the id isn't important. note either array1, array2, both or neither can present in document , can empty. have tried many aggregations , cascading query commands , can't come desired response.
to need use .aggregate() method provides access aggregation pipeline.
the first stage in pipeline uses $match operator filter out documents both array1 , array2 not presents using $exists operator , dot notation. operator reduce number of documents processed in down in pipeline.
the next stage $project use $setunion return array containing elements appear in of array; filters out duplicates elements in result. not use of $ifnull operator returns value of first expression or empty array depending on whether first expression evaluates null (here expression "array1" , "array2"). there, need de-normalize "arrays" field using $unwind operator.
in last stage of pipeline $group , use $addtoset accumulator operator returns array of unique value.
db.getcollection('collection').aggregate([ { "$match": { "$or": [ { "array1.0": { "$exists": true } }, { "array2.0": { "$exists": true } } ] }}, { "$project": { "arrays": { "$setunion": [ { "$ifnull": [ "$array1", [] ] }, { "$ifnull": [ "$array2", [] ] } ] } }}, { "$unwind": "$arrays" }, { "$group": { "_id": null, "arrays": { "$addtoset": "$arrays" } }} ] ) which yields:
{ "_id" : null, "arrays" : [ "5", "3", "1", "4", "2" ] }
Comments
Post a Comment