mongoDB – Multi update of documents
In mongoDB an update operation can be used in 4 ways
1. wholesale replacement of a document.
2. update individual field using $set operator
3. upsertĀ – do update or insert
4. multiupdate of a document
We have already read about first 3 let us look at multiupdate of a document.
if we run following command in mongoDB
> db.users.update({}, {$set:{"profession":"programmer"}});
As we have let first argument blank which acts as a where clause as in SQL. So from our SQL experience we know that when we do not specify where clause it updates all records in a table. So should same happen in mongoDB?
No, it is not true in case of mongoDB. This query will only update first matching record and will not update otehr records in collection.
To update all documents in a collection we need to add a third parameter in update as “multi : true”, now every matching document will be updated.
> db.users.update({}, {$set:{"profession":"programmer"}}, {multi: true});