- Reference >
mongo
Shell Methods >- Collection Methods >
- db.collection.update()
db.collection.update()¶
On this page
Definition¶
-
db.collection.
update
(query, update, options)¶ mongo
Shell MethodThis page documents the
mongo
shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.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¶
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. If set 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 New in version 3.4. |
||||||
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. New in version 3.6. |
||||||
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. |
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:
update
action on the specified collection(s).find
action on the specified collection(s).insert
action on the specified collection(s) if the operation results in an upsert.
The built-in role readWrite
provides the required
privileges.
Behavior¶
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 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. Before
MongoDB 4.2, a document’s shard key field value is immutable.
To modify the existing shard key value with
db.collection.update()
:
- You must run on a
mongos
. Do not issue the operation directly on the shard. - You must run either in a transaction or as a retryable write.
- You must specify
multi: false
. - You 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 must run on a
mongos
. Do not issue the operation directly on
the shard.
In addition, the following requirements also apply:
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 with feature compatibility version
(fcv) "4.4"
, you can create collections and indexes
inside a multi-document transaction if the transaction is
not a cross-shard write transaction.
As such, for the feature compatibility version (fcv) is "4.4"
or greater, db.collection.update()
with upsert:
true
can be run against an existing collection or a non-existing
collection. If run against a non-existing collection, the operation
creates the collection.
If the feature compatibility version (fcv) is
"4.2"
or less, the operation must be against 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¶
- Use Update Operator Expressions ($inc, $set)
- Push Elements to Existing Array
- Remove Fields ($unset)
- Replace Entire Document
- Update Multiple Documents
From the mongo
shell, create a books
collection which
contains the following documents. This command first removes all
previously existing documents from the books
collection:
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
$inc
operator increments thestock
field, and - the
$set
operator replaces the value of theitem
field,publisher
field in theinfo
embedded document,tags
field, and- second element in the
ratings
array.
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
From the mongo
shell, create a books
collection which
contains the following documents. This command first removes all
previously existing documents from the books
collection:
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
From the mongo
shell, create a books
collection which
contains the following documents. This command first removes all
previously existing documents from the books
collection:
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
From the mongo
shell, create a books
collection which
contains the following documents. This command first removes all
previously existing documents from the books
collection:
If the <update>
document contains only field:value
expressions, then:
- The
db.collection.update()
method replaces the matching document with the<update>
document. Thedb.collection.update()
method does not replace the_id
value. db.collection.update()
cannot update multiple documents.
The following operation passes an <update>
document that contains
only field and value pairs. The <update>
document completely
replaces the original document except for the _id
field.
You can use the web shell below to insert the sample documents and execute the example update operation:
The updated document contains only the fields from the
replacement document and the _id
field. As such, the fields
ratings
and reorder
no longer exist in the updated
document since the fields were not in the replacement document.
This operation corresponds to the following SQL statements:
From the mongo
shell, create a books
collection which
contains the following documents. This command first removes all
previously existing documents from the books
collection:
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.
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.
- Upsert with Replacement Document
- Upsert with Operator Expressions
- Aggregation Pipeline using Upsert
- Combine Upsert and Multi Options
- Upsert with Dotted _id Query
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
_id
field in either the query parameter or replacement document, MongoDB uses that_id
field in the inserted document.If you do not specify an
_id
field in either the query parameter or replacement document, MongoDB generates adds the_id
field with a randomly generated ObjectId value.Note
You cannot specify different
_id
field 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):
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
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
$replaceRoot
stage which can provide somewhat similar behavior to a$setOnInsert
update operator expression, - the
$set
stage which can provide similar behavior to the$set
update operator expression, - the aggregation variable
NOW
, which resolves to the current datetime and can provide similar behavior to the$currentDate
update 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.
Combine Upsert and Multi Options (Match)
From the mongo
shell, 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:
Combine Upsert and Multi Options (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):
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
Use Unique Indexes¶
Warning
To avoid inserting the same document more than once,
only use upsert: true
if the query
field is uniquely
indexed.
Given a collection named people
where no documents have
a name
field that holds the value Andy
, consider when multiple
clients issue the following db.collection.update()
with
upsert: true
at the same time:
If all db.collection.update()
operations complete the
query
portion before any client successfully inserts data, and
there is no unique index on the name
field, then each update
operation may result in an insert.
To prevent MongoDB from inserting the same document more than once,
create a unique index on the name
field.
With a unique index, if multiple applications issue the same update
with upsert: true
, exactly one
db.collection.update()
would successfully insert a new
document.
The remaining operations would either:
update the newly inserted document, or
fail when they attempted to insert a duplicate.
If the operation fails because of a duplicate index key error, applications may retry the operation which will succeed as an update operation.
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:
$addFields
and its alias$set
$project
and its alias$unset
$replaceRoot
and 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
comments
field and set thelastUpdate
field. - remove the
misc1
andmisc2
fields 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
$set
stage:- creates a new array field
comments
whose elements are the current content of themisc1
andmisc2
fields and - sets the field
lastUpdate
to the value of the aggregation variableNOW
. The aggregation variableNOW
resolves 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
$unset
stage removes themisc1
andmisc2
fields.
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
$set
stage:- calculates a new field
average
based on the average of thetests
field. See$avg
for more information on the$avg
aggregation operator and$trunc
for more information on the$trunc
truncate aggregation operator. - sets the field
lastUpdate
to the value of the aggregation variableNOW
. The aggregation variableNOW
resolves 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
$set
stage calculates a new fieldgrade
based on theaverage
field calculated in the previous stage. See$switch
for more information on the$switch
aggregation 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.
From the mongo
shell, 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.
From the mongo
shell, 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.
From the mongo
shell, 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.
Override Default Write Concern¶
The following operation on a replica set specifies a write
concern of "w: majority"
with a
wtimeout
of 5000 milliseconds such that the method returns after
the write propagates to a majority of the voting replica set members or
the method 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.
New in version 3.4.
From the mongo
shell, 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