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

160
Vistas
Conditional findoneandupdate in mongodb

I need to increment the counter field as long as it's less than 500 otherwise reset the counter to zero.

Here is my snippet:

StudentInfo.findOneAndUpdate(
    { studId: SID },
    **{ $inc: { counter: 1 } },**
    (err, studInfo) => {
        if (err || !studInfo) {
            console.log(err);
        } else {
            console.log(${JSON.stringify(studInfo));
        }
    },
);

How can I do it in a single update call?

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

0

You can do it with Aggregation framework:

  • $cond with $lt - To check if the current value of the counter is less than 500
  • $sum - To increase the current value of the counter by 1 if the condition is true
db.collection.update({
  "key": 1
},
[
  {
    "$set": {
      "counter": {
        $cond: {
          if: {
            $lt: [
              "$counter",
              500
            ]
          },
          then: {
            $sum: [
              "$counter",
              1
            ]
          },
          else: 0
        }
      }
    }
  }
],
{
  "multi": false,
  "upsert": false
})

Working example

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