MongoDB findOneAndUpdate for value less than other value

Issue

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 🙂

Solution

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})

Answered By – nimrod serok

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.