MongoDB: How to update multiple documents with a s

2019-01-01 05:33发布

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?

11条回答
美炸的是我
2楼-- · 2019-01-01 05:58

All latest versions of mongodb updateMany() is working fine

db.getCollection('workers').updateMany({},{$set: {"assignedVehicleId" : "45680"}});
查看更多
余生无你
3楼-- · 2019-01-01 05:59

For versions of mongodb 3.2+ you can use method updateMany() to update multiple documents,

http://answerexpress.blogspot.com/2018/09/mongodb-how-to-update-multiple.html

查看更多
骚的不知所云
4楼-- · 2019-01-01 06:05

In the MongoDB Client, type:

db.Collection.updateMany({}, $set: {field1: 'field1', field2: 'field2'})

New in version 3.2

Params::

{}:  select all records updated

Keyword argument multi not taken

查看更多
泪湿衣
5楼-- · 2019-01-01 06:08

I've created a way to do this with a better interface.

  • db.collection.find({ ... }).update({ ... }) -- multi update
  • db.collection.find({ ... }).replace({ ... }) -- single replacement
  • db.collection.find({ ... }).upsert({ ... }) -- single upsert
  • db.collection.find({ ... }).remove() -- multi remove

You can also apply limit, skip, sort to the updates and removes by chaining them in beforehand.

If you are interested, check out Mongo-Hacker

查看更多
泛滥B
6楼-- · 2019-01-01 06:11

For Mongo version > 2.2, add a field multi and set it to true

db.Collection.update({query}, 
                 {$set: {field1: "f1", field2: "f2"}},
                 {multi: true })
查看更多
美炸的是我
7楼-- · 2019-01-01 06:14

UPDATE as of V2.2, the update function takes the following form:

 db.collection.update(
   <query>,
   <update>,
   { upsert: <boolean>, multi: <boolean> }
)

The selected answer no longer applies.

https://docs.mongodb.com/manual/reference/method/db.collection.update/

查看更多
登录 后发表回答