db.collection.update()
On this page
Important
Deprecated mongosh Method
This method is deprecated in
mongosh
. For alternative
methods, see
Compatibility Changes with Legacy mongo Shell
.
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.
Compatibility
You can use
db.collection.update()
for deployments hosted in the following
environments:
-
MongoDB Atlas : The fully managed service for MongoDB deployments in the cloud
-
MongoDB Enterprise : The subscription-based, self-managed version of MongoDB
-
MongoDB Community : The source-available, free-to-use, and self-managed version of MongoDB
To learn how to update documents hosted in MongoDB Atlas by using the Atlas UI, see Edit One Document .
Syntax
Changed in version 5.0 .
The
db.collection.update()
method has the following form:
db.collection.update( <query>, <update>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string>, let: <document> // Added in MongoDB 5.0 } )
Parameters
The
db.collection.update()
method takes the following
parameters:
Parameter
|
Type
|
Description
|
||||||
---|---|---|---|---|---|---|---|---|
document
|
The selection criteria for the update. The same
query
selectors
as in the
When you execute an
|
|||||||
document or pipeline
|
The modifications to apply. Can be one of the following:
For details and examples, see Oplog Entries . |
|||||||
boolean
|
Optional. When
If both
To avoid multiple
upserts
, ensure that the
Defaults to
|
|||||||
boolean
|
Optional. If set to
|
|||||||
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
|
|||||||
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
|
|||||||
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
You cannot have an array filter document for an identifier if the identifier is not included in the update document.
For examples, see
Specify
|
|||||||
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
|
|||||||
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 (
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:
-
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
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.
Replace Document Operations on a Sharded Collection
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.
However, 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:
{ _id: <value>, <shardkeyfield>: null } // _id of the document missing shard key
Shard Key Modification
You can update a document's shard key value unless the shard key field is the
immutable
_id
field.
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
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:
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
distributed transactions
.
Important
In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed 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 distributed transactions.
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations .
Upsert within Transactions
You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.
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.
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 .
Oplog Entries
If a
db.collection.update()
operation successfully updates one or
more documents, the operation adds an entry on the
oplog
(operations log). If the operation fails or does not find any documents
to update, the operation does not add an entry on the oplog.
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:
db.books.remove({}); db.books.insertMany([ { "_id" : 1, "item" : "TBD", "stock" : 0, "info" : { "publisher" : "1111", "pages" : 430 }, "tags" : [ "technology", "computer" ], "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ], "reorder" : false }, { "_id" : 2, "item" : "XYZ123", "stock" : 15, "info" : { "publisher" : "5555", "pages" : 150 }, "tags" : [ ], "ratings" : [ { "by" : "xyz", "rating" : 5 } ], "reorder" : false } ]);
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:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Write Concern Errors
If the
db.collection.update()
method encounters write
concern errors, the results include the
WriteResult.writeConcernError
field:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1, "writeConcernError": { "code" : 64, "errmsg" : "waiting for replication timed out", "errInfo" : { "wtimeout" : true, "writeConcern" : { "w" : "majority", "wtimeout" : 100, "provenance" : "getLastErrorDefaults" } } })
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
|