Seven NoSQL Databases in a Week
上QQ阅读APP看书,第一时间看更新

The update operation

The following is a list of methods MongoDB uses to update the document information:

* db.collection.updateOne(<filter>, <update>, <options>);
* db.collection.updateMany(<filter>, <update>, <options>);
* db.collection.replaceOne(<filter>, <update>, <options>);

If the update operation increases the size of the document while updating, the update operation relocates the document on the disk:

  • Update single document: The following example uses the db.collection.updateOne() method to update a single document. The following query finds the userId 1 document in user_profiles and updates the age to 30:

Here, the query uses the $set operator to update the value of the age field, where the userId matches 1:

  • Update multiple documents: The following example uses the db.collection.updateMany() method to update multiple documents where the condition matches.

The following example updates the age of all users between the ages of 30 to 35:

The output gives us acknowledgement of how many documents have been updated:

  • Replace document: The db.collection.replaceOne() method replaces an entire document with a new document, except for the _id field. The _id field has the same value as the current document. The following example replaces a user's document with that of userId : 1:

The following are additional methods that can be used for the update operation:

  • db.collection.findOneAndReplace();
  • db.collection.findOneAndUpdate();
  • db.collection.findAndModify();
  • db.collection.save();
  • db.collection.bulkWrite();