MongoDB

Update

Posted on 02nd September 2014

The update() method updates one or more documents in a MongoDB collection. It can be used to update specific fields in a document (partial update) or replace the document entirely (full update). The syntax of update method is as below:

CollectionName - Name of the collection that contains the document(s) to update.

update_condition - Specifies the condition used to select the document(s) for update.

update_document - field:value expressions in case of full update or an expression containing update operators in case of a partial update

upsert - This parameter is optional. It can be set to true or false. If set to true, a new document is created when no document match the update condition. Default is false.

multi - This parameter is optional. It can be set to true or false. If set to true, all documents that match the update condition are updated. Default is false which updates a single document that match the update condition.

writeConcern - This parameter is optional. Write concern is the level of guarantee that MongoDB provides when reporting the result of a write operation. The default write concern level is Acknowledged. In this level mongod acknowledges the receipt of the write operation.

Full Update

If the update_document contains only field:value expressions, then a single document that match the update_condition is updated by default.

The update() method in the following example updates documents whose title field equals The Matrix with the field-value pairs in the second parameter (marked in red). Use the find() method to confirm the document has been successfully updated.

A full update entirely replaces the old document with the new document, except for the _id field. The _id field of a document cannot be updated.

Partial Update

Unlike a full update, you can modify specific fields and values of a document. This is achieved using update operators. The following table lists some of the commonly used update opertors

Operator

Description

$set

Set the value of a specified field

$unset

Remove the specified field

$rename

Rename the specified field

$inc

Increment the value of a field by the specified value

$currentDate

Sets a fields value to current date

$push

Add an item to an array

$pop

Remove an item from the array

If an update_document contains update operator expressions, then only the fields specified by those expressions are updated rather than the entire document.

In the example below the update operation is performed on the document that has the value The Matrix Reloaded in the title field. The $set operator adds a new field genre with the value Sci-Fi/Action . The $unset operator removes the field cast from the document.