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

193
Visualizações
MongoDB findOneAndUpdate for value less than other value

I can't seem to figure out the right syntax to update (increment) a value by 1 if one value is smaller than another. Here's some more details:

Data Structure

{
    "currentTask": 0,
    "maximumTask":10
}

What I want to do

  1. If there is a document where currentTask < maximumTask
  2. Retrieve that document
  3. Increment the currentTask value by 1

What I tried

let solver = await solvers.findOneAndUpdate({"currentTask":{"$lt": "$maximumTask"}},{"$inc":{"currentTask":1}});

I feel like I'm quite close but obviously new to MongoDB! Any help would be much appreciated :)

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

0

The syntax you use is for comparing a value that is on the document to an input value (which is not saved on the document). If you want to compare two values from the document, use $expr:

db.collection.findOneAndUpdate({
  $expr: {
    $lt: [
      "$currentTask",
      "$maximumTask"
    ]
  }
},
{
  $inc: {
    currentTask: 1
  }
})

Playground example

This answer will return the document before the update. To get the document after the update, use the options like this:

db.collection.findOneAndUpdate(
{$expr: {$lt: ["$currentTask", "$maximumTask"]}},
{$inc: {currentTask: 1}},
{returnNewDocument: 1})
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