How to make array elements unique in mongodb

Viewed 61

In my mongo collection, I have an array where all element have to be unique. But by mistake, I have added duplicate elements. How can I make array elements distinct? Is there any query/command?

document in collection:

{
   Tags: ["a", "a", "a"]
}

But I want:

{
  Tags: ["a"]
}
3 Answers

This looks like a nice option to clean duplicates from mongo shell:

 db.collection.aggregate([
    { "$project": {
        "Tags": { "$setUnion": [ "$Tags", [] ] },
        "same": { "$eq": [
        { "$size": "$Tags" },
        { "$size": { "$setUnion": [ "$Tags", [] ] } }
    ]}
  }},
   { "$match": { "same": false } }
 ]).forEach(function(doc) {
 db.collection.update(
    { "_id": doc._id },
    { "$set": { "Tags": doc.Tags } }
  )
 })

explained:

  1. project a new field "Tags" with only the unique values.
  2. Project a new field "same" that will check and say if there is duplicates.
  3. Match only the documents having duplicates
  4. Loop with forEach over the documents having duplicate tags to replace with the unique version.
Related