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
- If there is a document where
currentTask < maximumTask
- Retrieve that document
- 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 :)
CodePudding user response:
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
}
})
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})