5

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]
}
2
  • What are duplicates here? Commented Feb 4, 2014 at 7:11
  • @heinob 6 is the duplicate here Commented Feb 4, 2014 at 9:17

2 Answers 2

12

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

1 Comment

Nice. But if I have to join two array of objects. since set unions only with normal arrays.
5

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 Comments

$setUnion - This is exactly what I am looking for. Thanks for the info. I really need to do it using the aggregation framework. I have wait for the next release though :(
Is there any work around for this in the current version using the aggregation framework?

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.