0 votes
1 view
in Web Technology by (47.8k points)

I was surprised to find that the following example code only updates a single document:

> db.test.save({"_id":1, "foo":"bar"}); 

> db.test.save({"_id":2, "foo":"bar"}); 

> db.test.update({"foo":"bar"}, {"$set":{"test":"success!"}}); 

> db.test.find({"test":"success!"}).count(); 

1

I know I can loop through and keep updating until they're all changed, but that seems terribly inefficient. Is there a better way?

2 Answers

0 votes
by (107k points)

If you want to update multiple documents with a single command the use the below-mentioned code:-

db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true);

0 votes
by (78.7k points)

For versions of MongoDB 3.2+, you can use a new method updateMany() to update multiple documents at once, without the need of separate multi-option.

db.test.updateMany({foo: "bar"}, {$set: {test: "success!"}})

Related questions

0 votes
2 answers
asked Oct 16, 2019 in Web Technology by Sammy (47.8k points)
0 votes
2 answers
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...