Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda