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

192
Views
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 answers
Answer question

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 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!