Merge two array field in mongoDB

2019-01-20 15:50发布

问题:

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

回答1:

If you want to modify your data you can use $addToSet with the $each modifier once you have read the contents of one of the arrays. These would be individual updates as you cannot refer to another element of the document in an update operation.

If you really just want this for aggregation and can wait, then the upcoming release of MongoDB adds new set operators to aggregation. Particularly there is $setUnion which will do exactly what you want.



回答2:

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