Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k 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 (106k 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 (108k 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.6k points)
0 votes
2 answers
asked Oct 16, 2019 in Web Technology by Sammy (47.6k points)
0 votes
2 answers

Browse Categories

...