Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda