Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

248
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda