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

695
Vistas
Update a field only if it exists in MongoDB

I have a document in collection testcol in MongoDB like this :

{
_id:111,
"xxx":"aaa",
"yyy":"bbb"
}

I want to update the field yyy in the document, if the field is found then update it and if the field is not found then don't do anything.

When I am running my mongo db update command like db.testcol.update({_id:0},{$set:{"zzz":"ccc"}},{upsert: false}). Intentionally I gave the field as "zzz" in the update command so that it shouldn't do anything. But when I run the above update command, it inserted the new field "zzz" in the above document although upsert was given false. I know upsert will not/will insert document and not field , but since I am new to MongoDB I was just giving it a try. Can anyone please let me know how to approach this issue?

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

0

You can use the $exists operator in your query to only match the document if the yyy field is present:

db.testcol.update({_id: 111, yyy: {$exists: true}}, {$set: {yyy: 'ccc'}})
over 4 years ago · Santiago Trujillo Denunciar

0

You are using upsert wrong. Please see mongo's docs here

If upsert is true and no document matches the query criteria, update() inserts a single document. The update creates the new document. If upsert is true and there are documents that match the query criteria, update() performs an update.

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