Willem van der Veen
Willem van der Veen

Reputation: 36580

Update field using the existing value

Working with the following MongoDB version (package.json content):

"mongodb": "^3.0.2"

And I have the following code:

const addValue = 10;

await db.db('dbname').collection('collname').updateOne({
        bar: bar
    }, {
        $set: {
            foo: foo
        }
     }
);

I want to set the variable foo to the old value of foo + the addValue variable. Something like this in pseudo code:

$set: {
    foo: foo + addValue 
}

When implementing this code I get the following I get a referenceError:

 C:\Users\wille\Desktop\Projects\nv\server\XXX_playground.js:28
             foo: foo  + addValue
                         ^

 **ReferenceError**: foo is not defined
     at Timeout.test [as _onTimeout] (C:\Users\wille\Desktop\Projects\nv\server\XXX_playground.js:28:26)
     at ontimeout (timers.js:424:11)
     at tryOnTimeout (timers.js:288:5)
     at listOnTimeout (timers.js:251:5)
     at Timer.processTimers (timers.js:211:10) PS C:\Users\wille\Desktop\Projects\nv\server>

I simply first could query the foo variable with findOne store it in a variable, and then use it in the updateOne. However, this would result in 2 queries and seems a bit suboptimal.

Question:

Is there a way of doing this in one query?

Upvotes: 1

Views: 43

Answers (1)

Luca Kiebel
Luca Kiebel

Reputation: 10096

Mongoose's $inc operator accepts increment values as the values of the object passed to it:

const addValue = 10;

await db.db('dbname').collection('collname').updateOne({
    bar: bar
}, {
    $inc: {
        foo: addValue // the value you want to increment by
    }
});

Upvotes: 1

Related Questions