Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

326
Views
En updateMany, actualice el campo solo si el campo existe y no cree una nueva clave

Entonces, lo que quiero hacer dentro de $set es verificar si el campo existe y luego actualizar el valor, pero solo si este campo existe. El $cond está muy cerca de lo que quiero lograr, pero el problema es que no puedo evitar que cree el campo.

Podría filtrar para obtener solo el campo existente, pero en este caso tendría que actualizar campo por campo en lugar de todos al mismo tiempo, y esto llevaría una eternidad.

 const data = await connection.collection("snapshot").updateMany({}, [ { $set: { field1: { $cond: [ { field1: { $exists: true } }, { field1: "newValue" }, undefined, // do nothing ], }, field2: { $cond: [ { field2: { $exists: true } }, { field2: "newValue" }, undefined, // do nothing ], }, field3: { $cond: [ { field3: { $exists: true } }, { field3: "newValue" }, undefined, // do nothing ], }, }, }, ]);

¿Me estoy perdiendo algo o simplemente es imposible de hacer?

estoy usando mongo 5.0

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El operador $exists solo funciona en find , no en Aggregation Pipelines. Verificar que "el campo existe" no es trivial, consulte O con If e In mongodb

Supongo que le gusta actualizar documentos como { field3: "newValue" } , su actualización hará { field3: { field3: "newValue" } }

Sobre todo seria este:

 connection.collection("snapshot").updateMany({}, [ { $set: { field1: { $cond: [ { $ne: [{ $type: "$field1" }, "missing"] }, "newValue", "$$REMOVE" // do nothing ] }, field2: { $cond: [ { $ne: [{ $type: "$field2" }, "missing"] }, "newValue", "$$REMOVE" // do nothing ] }, field3: { $cond: [ { $ne: [{ $type: "$field3" }, "missing"] }, "newValue", "$$REMOVE" // do nothing ] } } } ])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!