Rahul Kumar
Rahul Kumar

Reputation: 99

MongoDb - Equivalent for traditional update-set-where

Does mongo have an equivalent for

update emp
set sal = sal * 1.20
where empno in (1,2,3);

Note that I want the matched records sal.

db.users.update(
    { empno: { $in: [1,2,3]} },
    { $set: { sal: $matched.sal * 1.20 } }, # Not real syntax
    { multi: true }
)

I have looked through the documentation but couldn't find anything. I can do it with find-save but I am dealing with a large collection and multi update will be a more desirable solution.

Upvotes: 1

Views: 206

Answers (2)

diversario
diversario

Reputation: 1014

Unfortunately, this is not possible with MongoDB. The closes you could get is with $where operator, but reference specifically warns against updating documents from $where. So, yes, you will have to fetch documents one by one and perform updates individually.

Upvotes: 1

Sergey Gavruk
Sergey Gavruk

Reputation: 3568

In mongo shell there is no such function as multiply element. There are few field update operators, but in your situation you need to run a custom forEach script:

db.users.find({ empno: { $in: [1,2,3]} }).forEach(function(e) {
    e.sal = e.sal * 1.2;
    db.users.save(e);
});

Upvotes: 1

Related Questions