[mongodb] MongoDB: How to update multiple documents with a single command?

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?

This question is related to mongodb document nosql

The answer is


All latest versions of mongodb updateMany() is working fine

db.getCollection('workers').updateMany({},{$set: {"assignedVehicleId" : "45680"}});

To Update Entire Collection,

db.getCollection('collection_name').update({},
{$set: {"field1" : "value1", "field2" : "value2", "field3" : "value3"}},
{multi: true })

The following command can update multiple records of a collection

db.collection.update({}, 
{$set:{"field" : "value"}}, 
{ multi: true, upsert: false}
)

Thanks for sharing this, I used with 2.6.7 and following query just worked,

for all docs:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})

for single doc:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})

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


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 })

You can use.`

        Model.update({
            'type': "newuser"
        }, {
            $set: {
                email: "[email protected]",
                phoneNumber:"0123456789"
            }
        }, {
            multi: true
        },
        function(err, result) {
            console.log(result);
            console.log(err);
        })  `

MongoDB will find only one matching document which matches the query criteria when you are issuing an update command, whichever document matches first happens to be get updated, even if there are more documents which matches the criteria will get ignored.

so to overcome this we can specify "MULTI" option in your update statement, meaning update all those documnets which matches the query criteria. scan for all the documnets in collection finding those which matches the criteria and update :

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

Starting in v3.3 You can use updateMany

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ]
   }
)

In v2.2, the update function takes the following form:

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

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


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


I had the same problem , and i found the solution , and it works like a charm

just set the flag multi to true like this :

 db.Collection.update(
                {_id_receiver: id_receiver},
               {$set: {is_showed: true}},
                {multi: true}   /* --> multiple update */
            , function (err, updated) {...});

i hope that helps :)


Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to document

Selenium wait until document is ready GetElementByID - Multiple IDs Difference between $(document.body) and $('body') How do I convert a org.w3c.dom.Document object to a String? Convert Mongoose docs to json Create auto-numbering on images/figures in MS Word Accessing elements by type in javascript $(window).scrollTop() vs. $(document).scrollTop() Get IFrame's document, from JavaScript in main document "Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

Examples related to nosql

Firestore Getting documents id from collection What is Hash and Range Primary Key? Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061 Explanation of JSONB introduced by PostgreSQL DynamoDB vs MongoDB NoSQL Querying DynamoDB by date Delete all nodes and relationships in neo4j 1.8 When to use CouchDB over MongoDB and vice versa Difference between scaling horizontally and vertically for databases NoSQL Use Case Scenarios or WHEN to use NoSQL