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

272
Vistas
MongoDB query for adding to array if not present

I am new to MongoDB and want to know if there is any way to add an embedded document to an array if it is not present.

Let's say I have a collection called products:

{
    _id: "123",
    name: "Hair-Dryer",
    locations: [{
            code: "MA",
            name: "Massachusetts"
        },
        {
            code: "IL",
            name: "illinois"
        }
    ]
}, {
    _id: "456",
    name: "Toaster",
    locations: [{
        code: "MA",
        name: "Massachusetts"
    }, ]
}

Now lets say I want to add :

{
        code: "IL",
        name: "illinois"
}

To only those documents which don't have them. Note that, I don't know which documents have my required data or which don't have them. I need to find that out.

How can I write a query like this in MongoDB ?

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

0

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.

Try this:

db.locations.updateMany({}, {
    $addToSet: {
        locations: {
            code: "IL",
            name: "illinois"
        }
    }
});
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