Home > Net >  How to make array elements unique in mongodb
How to make array elements unique in mongodb

Time:01-06

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

CodePudding user response:

For mongo version 4.2 you can just use pipelined updates combined with $setUnion, like so:

db.collection.updateMany({},
[
  {
    $set: {
      Tags: {
        $setUnion: "$Tags"
      }
    }
  }
])

Mongo Playground

CodePudding user response:

You can create a unique index on the tag property of the collection in question.

Please refer to the following official guide;

https://docs.mongodb.com/manual/core/index-unique/

CodePudding user response:

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.
  •  Tags:  
  • Related