- Reference >
mongoshMethods >- Collection Methods >
- db.collection.update()
db.collection.update()¶
On this page
Important
Deprecated mongosh Method
This method is deprecated in mongosh. For alternative
methods, see compatibility.
Definition¶
-
db.collection.update(query, update, options)¶ Modifies an existing document or documents in a collection. The method can modify specific fields of an existing document or documents or replace an existing document entirely, depending on the update parameter.
By default, the
db.collection.update()method updates a single document. Include the option multi: true to update all documents that match the query criteria.
Syntax¶
Changed in version 5.0.
The db.collection.update() method has the following form:
Parameters¶
The db.collection.update() method takes the following
parameters:
| Parameter | Type | Description | ||||||
|---|---|---|---|---|---|---|---|---|
| query | document | The selection criteria for the update. The same query
selectors as in the When you execute an |
||||||
| update | document or pipeline | The modifications to apply. Can be one of the following:
For details and examples, see Examples. |
||||||
| upsert | boolean | Optional. When
If both To avoid multiple upserts, ensure that the
Defaults to |
||||||
| multi | boolean | Optional. If set to |
||||||
| writeConcern | document | Optional. A document expressing the write concern. Omit to use the default write
concern Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern. For an example using |
||||||
| collation | document | Optional. Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. For an example using |
||||||
| arrayFilters | array | Optional. An array of filter documents that determine which array elements to modify for an update operation on an array field. In the update document, use the
Note You cannot have an array filter document for an identifier if the identifier is not included in the update document. For examples, see Specify arrayFilters for Array Update Operations. |
||||||
| hint | Document or string | Optional. A document or string that specifies the index to use to support the query predicate. The option can take an index specification document or the index name string. If you specify an index that does not exist, the operation errors. For an example, see Specify hint for Update Operations. New in version 4.2. |
||||||
| let | document | Optional. Specifies a document with a list of variables. This allows you to improve command readability by separating the variables from the query text. The document syntax is: The variable is set to the value returned by the expression, and cannot be changed afterwards. To access the value of a variable in the command, use the double
dollar sign prefix ( Note To use a variable to filter results, you must access the variable
within the For a complete example using New in version 5.0. |
Returns¶
The method returns a WriteResult document that contains the status of the operation.
Access Control¶
On deployments running with authorization, the
user must have access that includes the following privileges:
updateaction on the specified collection(s).findaction on the specified collection(s).insertaction on the specified collection(s) if the operation results in an upsert.
The built-in role readWrite provides the required
privileges.
Behavior¶
Using $expr in an Update with Upsert¶
Attempting to use the $expr
operator with the upsert flag set to true will generate an error.
Sharded Collections¶
To use db.collection.update() with multi: false on a
sharded collection, you must include an exact match on the _id
field or target a single shard (such as by including the shard key).
When the db.collection.update() performs update operations
(and not document replacement operations),
db.collection.update() can target multiple shards.
See also
Replace Document Operations on a Sharded Collection¶
Starting in MongoDB 4.2, replace document operations attempt to target a single shard, first by using the query filter. If the operation cannot target a single shard by the query filter, it then attempts to target by the replacement document.
In earlier versions, the operation attempts to target using the replacement document.
upsert on a Sharded Collection¶
For a db.collection.update() operation that includes
upsert: true and is on a sharded collection, you
must include the full shard key in the filter:
- For an update operation.
- For a replace document operation (starting in MongoDB 4.2).
However, starting in version 4.4, documents in a sharded collection can be
missing the shard key fields. To target a
document that is missing the shard key, you can use the null
equality match :red:`in conjunction with` another filter condition
(such as on the _id field). For example:
Shard Key Modification¶
Starting in MongoDB 4.2, you can update a document’s shard key value
unless the shard key field is the immutable _id field. In
MongoDB 4.2 and earlier, a document’s shard key field value is
immutable.
To modify the existing shard key value with
db.collection.update():
- You :red:`must` run on a
mongos. Do :red:`not` issue the operation directly on the shard. - You :red:`must` run either in a transaction or as a retryable write.
- You :red:`must` specify
multi: false. - You :red:`must` include an equality query filter on the full shard key.
Tip
Since a missing key value is returned as part of a null equality
match, to avoid updating a null-valued key, include additional
query conditions (such as on the _id field) as appropriate.
See also upsert on a Sharded Collection.
Missing Shard Key¶
Starting in version 4.4, documents in a sharded collection can be
missing the shard key fields. To use
db.collection.update() to set the document’s
missing shard key, you :red:`must` run on a
mongos. Do :red:`not` issue the operation directly on
the shard.
In addition, the following requirements also apply:
| Task | Requirements |
|---|---|
To set to null |
|
To set to a non-null value |
|
Tip
Since a missing key value is returned as part of a null equality
match, to avoid updating a null-valued key, include additional
query conditions (such as on the _id field) as appropriate.
See also:
Transactions¶
db.collection.update() can be used inside multi-document transactions.
Important
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.
Upsert within Transactions¶
Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is :red:`not` a cross-shard write transaction.
Specifically, in MongoDB 4.4 and greater, db.collection.update() with
upsert: true can be run on an existing collection or a
non-existing collection. If run on a non-existing collection,
the operation creates the collection.
In MongoDB 4.2 and earlier, the operation must be run on an existing collection.
Write Concerns and Transactions¶
Do not explicitly set the write concern for the operation if run in a transaction. To use write concern with transactions, see Transactions and Write Concern.
Examples¶
The following tabs showcase a variety of common
update() operations.
In mongosh, create a books collection which
contains the following documents. This command first removes all
previously existing documents from the books collection:
- Set
- Arrays
- Unset
- Multiple
Use Update Operator Expressions (``$inc`` and ``$set``)
If the <update> document contains update operator modifiers, such as those using the
$set modifier, then:
- The
<update>document must contain only update operator expressions. - The
db.collection.update()method updates only the corresponding fields in the document.- To update an embedded document or an array as a whole, specify the replacement value for the field.
- To update particular fields in an embedded document or in an array, use dot notation to specify the field.
You can use the web shell below to insert the sample documents and execute the example update operation:
In this operation:
- The
<query>parameter of{ _id: 1 }specifies which document to update, - the
$incoperator increments thestockfield, and - the
$setoperator replaces the value of theitemfield,publisherfield in theinfoembedded document,tagsfield, and- second element in the
ratingsarray.
The updated document is the following:
This operation corresponds to the following SQL statement:
Note
If the query parameter had matched multiple documents,
this operation would only update one matching document. To
update multiple documents, you must set the multi option
to true.
See also
Push Elements to Existing Array (``$push``)
The following operation uses the $push update
operator to append a new object to the ratings array.
You can use the web shell below to insert the sample documents and execute the example update operation:
The updated document is the following:
See also
Remove Fields (``$unset``)
The following operation uses the $unset operator to remove
the tags field from the document with { _id: 1 }.
You can use the web shell below to insert the sample documents and execute the example update operation:
The updated document is the following:
There is not a direct SQL equivalent to $unset,
however $unset is similar to the following SQL
command which removes the tags field from the books
table:
See also
Update Multiple Documents (``$update`` With ``multi``)
If multi is set to true, the
db.collection.update() method updates all documents
that meet the <query> criteria. The multi update
operation may interleave with other read/write operations.
The following operation sets the reorder field to true
for all documents where stock is less than or equal to
10. If the reorder field does not exist in the matching
document(s), the $set operator adds the field
with the specified value.
You can use the web shell below to insert the sample documents and execute the example update operation:
The resulting documents in the collection are the following:
This operation corresponds to the following SQL statement:
Note
You cannot specify multi: true when performing a
replacement, i.e., when the <update> document contains only
field:value expressions.
See also
Insert a New Document if No Match Exists (Upsert)¶
When you specify the option upsert: true:
If document(s) match the query criteria,
db.collection.update()performs an update.If no document matches the query criteria,
db.collection.update()inserts a single document.Note
If multiple, identical upserts are issued at roughly the same time, it is possible for
update()used with upsert: true to create duplicate documents. See Upsert with Unique Index for more information.
If you specify upsert: true on a sharded collection, you must
include the full shard key in the filter. For additional
db.collection.update() behavior on a sharded collection, see
Sharded Collections.
The following tabs showcase a variety of uses of the upsert modifier
with update().
- Replace
- Set
- Aggregation
- Multiple
- Dotted ``_id``
Upsert with Replacement Document
If no document matches the query criteria and the <update>
parameter is a replacement document (i.e., contains only field
and value pairs), the update inserts a new document with the
fields and values of the replacement document.
If you specify an
_idfield in either the query parameter or replacement document, MongoDB uses that_idfield in the inserted document.If you do not specify an
_idfield in either the query parameter or replacement document, MongoDB generates adds the_idfield with a randomly generated ObjectId value.Note
You cannot specify different
_idfield values in the query parameter and replacement document. If you do, the operation errors.
For example, the following update sets the upsert option to true:
If no document matches the <query> parameter, the update
operation inserts a document with only the replacement
document. Because no _id field was specified in the
replacement document or query document, the operation creates a
new unique ObjectId for the new document’s _id field.
You can see the upsert reflected in the WriteResult of the operation:
The operation inserts the following document into the books
collection (your ObjectId value will differ):
Upsert with Operator Expressions (``$set``)
If no document matches the query criteria and the <update>
parameter is a document with update operator expressions, then the operation creates a base document
from the equality clauses in the <query> parameter and
applies the expressions from the <update> parameter.
Comparison operations from
the <query> will not be included in the new document. If
the new document does not include the _id field, MongoDB
adds the _id field with an ObjectId value.
For example, the following update sets the upsert option to true:
If no documents match the query condition, the operation inserts the following document (your ObjectId value will differ):
See also
Upsert using an Aggregation Pipeline
If the <update> parameter is an aggregation pipeline, the update creates a base
document from the equality clauses in the <query>
parameter, and then applies the pipeline to the document to
create the document to insert. If the new document does not
include the _id field, MongoDB adds the _id field with
an ObjectId value.
For example, the following upsert: true operation specifies an aggregation pipeline that uses
- the
$replaceRootstage which can provide somewhat similar behavior to a$setOnInsertupdate operator expression, - the
$setstage which can provide similar behavior to the$setupdate operator expression, - the aggregation variable
NOW, which resolves to the current datetime and can provide similar behavior to the$currentDateupdate operator expression.
If no document matches the <query> parameter, the
operation inserts the following document into the books
collection (your ObjectId value will differ):
See also
For additional examples of updates using aggregation pipelines, see Update with Aggregation Pipeline.
Using ``upsert`` with ``multi`` (Match)
From mongosh, insert the following
documents into a books collection:
The following operation specifies both the multi option and
the upsert option. If matching documents exist, the
operation updates all matching documents. If no matching
documents exist, the operation inserts a new document.
The operation updates all matching documents and results in the following:
Using ``upsert`` with ``multi`` (No Match)
If the collection had no matching document, the operation
would result in the insertion of a single document using the
fields from both the <query> and the <update>
specifications. For example, consider the following operation:
The operation inserts the following document into the books
collection (your ObjectId value will differ):
Upsert with Dotted ``_id`` Query
When you execute an update() with upsert:
true and the query matches no existing document, MongoDB will refuse
to insert a new document if the query specifies conditions on the
_id field using dot notation.
This restriction ensures that the order of fields embedded in the
_id document is well-defined and not bound to the order specified in
the query.
If you attempt to insert a document in this way, MongoDB will raise an
error. For example, consider the following update operation. Since the
update operation specifies upsert:true and the query specifies
conditions on the _id field using dot notation, then the update will
result in an error when constructing the document to insert.
The WriteResult of the operation returns the following
error:
See also
Upsert with Unique Index¶
When using the upsert: true option with the update()
method, and not using a unique index on the query field(s), multiple
instances of a update() operation with similar query
field(s) could result in duplicate documents being inserted in
certain circumstances.
Consider an example where no document with the name Andy exists
and multiple clients issue the following command at roughly the same
time:
If all update() operations finish the query phase
before any client successfully inserts data, and there is no
unique index on the name field, each
update() operation may result in an insert, creating multiple
documents with name: Andy.
To ensure that only one such document is created, and the other
update() operations update this new document instead, create a
unique index on the name field. This
guarantees that only one document with name: Andy is permitted
in the collection.
With this unique index in place, the multiple update() operations
now exhibit the following behavior:
- Exactly one
update()operation will successfully insert a new document. - All other
update()operations will update the newly-inserted document, incrementing thescorevalue.
See also
Update with Aggregation Pipeline¶
Starting in MongoDB 4.2, the db.collection.update() method
can accept an aggregation pipeline [ <stage1>, <stage2>, ... ] that
specifies the modifications to perform. The pipeline can consist of
the following stages:
$addFieldsand its alias$set$projectand its alias$unset$replaceRootand its alias$replaceWith.
Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).
Modify a Field Using the Values of the Other Fields in the Document¶
Create a members collection with the following documents:
Assume that instead of separate misc1 and misc2 fields, you
want to gather these into a new comments field. The following
update operation uses an aggregation pipeline to:
- add the new
commentsfield and set thelastUpdatefield. - remove the
misc1andmisc2fields for all documents in the collection.
Note
The $set and $unset used in the pipeline refers to the
aggregation stages $set and $unset
respectively, and not the update operators $set and
$unset.
- First Stage
The
$setstage:- creates a new array field
commentswhose elements are the current content of themisc1andmisc2fields and - sets the field
lastUpdateto the value of the aggregation variableNOW. The aggregation variableNOWresolves to the current datetime value and remains the same throughout the pipeline. To access aggregation variables, prefix the variable with double dollar signs$$and enclose in quotes.
- creates a new array field
- Second Stage
- The
$unsetstage removes themisc1andmisc2fields.
After the command, the collection contains the following documents:
See also
Perform Conditional Updates Based on Current Field Values¶
Create a students3 collection with the following documents:
Using an aggregation pipeline, you can update the documents with the calculated grade average and letter grade.
Note
The $set used in the pipeline refers to the aggregation stage
$set, and not the update operators $set.
- First Stage
The
$setstage:- calculates a new field
averagebased on the average of thetestsfield. See$avgfor more information on the$avgaggregation operator and$truncfor more information on the$trunctruncate aggregation operator. - sets the field
lastUpdateto the value of the aggregation variableNOW. The aggregation variableNOWresolves to the current datetime value and remains the same throughout the pipeline. To access aggregation variables, prefix the variable with double dollar signs$$and enclose in quotes.
- calculates a new field
- Second Stage
- The
$setstage calculates a new fieldgradebased on theaveragefield calculated in the previous stage. See$switchfor more information on the$switchaggregation operator.
After the command, the collection contains the following documents:
See also
Specify arrayFilters for Array Update Operations¶
In the update document, use the $[<identifier>] filtered
positional operator to define an identifier, which you then reference
in the array filter documents. You cannot have an array filter
document for an identifier if the identifier is not included in the
update document.
Note
The <identifier> must begin with a lowercase letter and
contain only alphanumeric characters.
You can include the same identifier multiple times in the update
document; however, for each distinct identifier ($[identifier])
in the update document, you must specify exactly one
corresponding array filter document. That is, you cannot specify
multiple array filter documents for the same identifier. For
example, if the update statement includes the identifier x
(possibly multiple times), you cannot specify the following for
arrayFilters that includes 2 separate filter documents for x:
However, you can specify compound conditions on the same identifier in a single filter document, such as in the following examples:
arrayFilters is not available for updates that use an
aggregation pipeline.
Update Elements Match arrayFilters Criteria¶
To update all array elements which match a specified criteria, use the arrayFilters parameter.
In mongosh, create a students
collection with the following documents:
To update all elements that are greater than or equal to 100 in the
grades array, use the filtered positional operator
$[<identifier>] with the arrayFilters option:
After the operation, the collection contains the following documents:
Update Specific Elements of an Array of Documents¶
You can also use the arrayFilters parameter to update specific document fields within an array of documents.
In mongosh, create a students2
collection with the following documents:
To modify the value of the mean field for all elements in the
grades array where the grade is greater than or equal to 85,
use the filtered positional operator $[<identifier>] with
the arrayFilters:
After the operation, the collection has the following documents:
Specify hint for Update Operations¶
New in version 4.2.
In mongosh, create a members
collection with the following documents:
Create the following indexes on the collection:
The following update operation explicitly hints to
use the index {status: 1 }:
Note
If you specify an index that does not exist, the operation errors.
The update command returns the following:
To see the index used, run explain on the operation:
The db.collection.explain().update()
does not modify the documents.
Use Variables in let¶
New in version 5.0.
To define variables that you can access elsewhere in the command, use the let option.
Note
To filter results using a variable, you must access the variable
within the $expr operator.
Create a collection cakeFlavors:
The following example defines targetFlavor and newFlavor
variables in let and uses the variables to change the cake flavor
from cherry to orange:
Override Default Write Concern¶
The following operation to a replica set specifies a write concern of w: 2 with a wtimeout of 5000
milliseconds. This operation either returns after the write propagates
to both the primary and one secondary, or times out after 5 seconds.
Specify Collation¶
Specifies the collation to use for the operation.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
The collation option has the following syntax:
When specifying collation, the locale field is mandatory; all
other collation fields are optional. For descriptions of the fields,
see Collation Document.
If the collation is unspecified but the collection has a
default collation (see db.createCollection()), the
operation uses the collation specified for the collection.
If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.
You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.
In mongosh, create a collection named
myColl with the following documents:
The following operation includes the collation
option and sets multi to true to update all matching documents:
The write result of the operation returns the following document, indicating that all three documents in the collection were updated:
After the operation, the collection contains the following documents:
WriteResult¶
Successful Results¶
The db.collection.update() method returns a
WriteResult object that contains the status of the operation.
Upon success, the WriteResult object contains the number of
documents that matched the query condition, the number of documents
inserted by the update, and the number of documents modified:
Write Concern Errors¶
If the db.collection.update() method encounters write
concern errors, the results include the
WriteResult.writeConcernError field:
Changed in version 4.4.
The following table explains the possible values of
WriteResult.writeConcernError.provenance:
| Provenance | Description |
|---|---|
clientSupplied |
The write concern was specified in the application. |
customDefault |
The write concern originated from a custom defined
default value. See setDefaultRWConcern. |
getLastErrorDefaults |
The write concern originated from the replica set’s
settings.getLastErrorDefaults field. |
implicitDefault |
The write concern originated from the server in absence of all other write concern specifications. |
See also