Merge two array fields in mongoDB
aggregation-framework, mongodb, mongodb-query
Solution
Using the `.aggregate()` method and the `$setUnion` operator.
db.collection.aggregate([
{ "$project": {
"attribute3": { "$setUnion": [ "$attribute1", "$attribute2" ] }
}}
])
Which yields:
{
"_id" : ObjectId("52f0795a58c5061aa34d436a"),
"attribute3" : [8, 4, 2, 6, 3, 7, 1]
}
Problem
I have a collection of the following structure ``` { _id : ObjectId("52f0795a58c5061aa34d436a"), "attribute1" : [1, 3, 6, 7], "attribute2" : [2, 4, 6, 8] } ``` Is there any way I can merge the two attributes while removing duplicates using aggregation query in mongoDB? I need the result to be like this: ``` { _id : ObjectId("52f0795a58c5061aa34d436a"), "attribute3" : [1, 3, 6, 7, 2, 4, 8] } ```