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

793
Vistas
How do I merge arrays from multiple documents without duplicates in MongoDB aggregation?

I have 3 documents:

{
  "id": 1,
  "user": "Brian1",
  "configs": [
    "a",
    "b",
    "c",
    "d"
  ]
}

----

{
  "id": 2,
  "user": "max_en",
  "configs": [
    "a",
    "h",
    "i",
    "j"
  ]
}

----

----

{
  "id": 3,
  "user": "userX",
  "configs": [
    "t",
    "u",
    "s",
    "b"
  ]
}

I want to merge all the "configs" arrays into one array without dublicates,like this:

{
"configs": [
  "a",
  "b",
  "c",
  "d",
  "h",
  "i",
  "j",
  "t",
  "u",
  "s",
  ]
}

I've tried the following:

Aggregation.group("").addToSet("configs").as("configs") and { _id: "", 'configs': { $addToSet: '$configs' } }

The first one gives an error because I've left the fieldname empty (I don't know what to put there).

The second one returns a merged array but with duplicates.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

When you want to group all the documents, you need to add {_id: null}

It means group all documents.

Probably you need this

db.collection.aggregate([
  {
    "$unwind": "$configs"
  },
  {
    $group: {
      _id: null,
      configs: {
        "$addToSet": "$configs"
      }
    }
  }
])

But be cautious when you need to use on larger collection without a match.

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