Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to make array elements unique in mongodb

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"]
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report

0

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/

over 4 years ago · Santiago Trujillo Report

0

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.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!