- Reference >
mongo
Shell Methods >- Collection Methods >
- db.collection.updateMany()
db.collection.updateMany()¶
On this page
Definition¶
-
db.collection.
updateMany
(filter, 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.New in version 3.2.
Updates all documents that match the specified filter for a collection.
Syntax¶
The updateMany()
method has the following form:
Parameters¶
The updateMany()
method takes the following
parameters:
Parameter | Type | Description | ||||
---|---|---|---|---|---|---|
filter | document | The selection criteria for the update. The same query
selectors as in the Specify an empty document |
||||
update | document or pipeline | The modifications to apply. Can be one of the following:
To update with a replacement document, see
|
||||
upsert |
boolean | Optional. When
To avoid multiple upserts, ensure that the Defaults 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. |
||||
collation |
document | Optional. 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 If the collation is unspecified but the collection has a
default collation (see 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. |
||||
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 The You can include the same identifier multiple times in the update
document; however, for each distinct identifier ( However, you can specify compound conditions on the same identifier in a single filter document, such as in the following examples: For examples, see Specify arrayFilters for an 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.1. |
Returns¶
The method returns a document that contains:
- A boolean
acknowledged
astrue
if the operation ran with write concern orfalse
if write concern was disabled matchedCount
containing the number of matched documentsmodifiedCount
containing the number of modified documentsupsertedId
containing the_id
for the upserted document
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¶
updateMany()
updates all matching documents in
the collection that match the filter
, using the update
criteria
to apply modifications.
Upsert¶
If upsert: true
and no documents match the filter
,
db.collection.updateMany()
creates a new
document based on the filter
and update
parameters.
If you specify upsert: true
on a sharded collection, you must
include the full shard key in the filter
. For additional
db.collection.updateMany()
behavior, see
Sharded Collections.
Update with an Update Operator Expressions Document¶
For the modification specification, the
db.collection.updateMany()
method can accept a document that
only contains update operator expressions to
perform.
For example:
Update with an Aggregation Pipeline¶
Starting in MongoDB 4.2, the db.collection.updateMany()
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).
For example:
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
.
For examples, see Update with Aggregation Pipeline.
Capped Collections¶
If an update operation changes the document size, the operation will fail.
Sharded Collections¶
For a db.collection.updateMany()
operation that includes
upsert: true
and is on a sharded collection, you must include the
full shard key in the filter
.
Transactions¶
db.collection.updateMany()
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.updateMany()
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¶
Update Multiple Documents¶
The restaurant
collection contains the following documents:
The following operation updates all documents where violations
are
greater than 4
and $set
a flag for review:
The operation returns:
The collection now contains the following documents:
If no matches were found, the operation instead returns:
Setting upsert: true
would insert a document if no match was found.
Update with Aggregation Pipeline¶
Starting in MongoDB 4.2, the db.collection.updateMany()
can use
an aggregation pipeline for the update. 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).
Example 1¶
The following examples uses the aggregation pipeline to 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:
Example 2¶
The aggregation pipeline allows the update to perform conditional updates based on the current field values as well as use current field values to calculate a separate field value.
For example, 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
Update Multiple Documents with Upsert¶
The inspectors
collection contains the following documents:
The following operation updates all documents with Sector
greater
than 4 and inspector
equal to "R. Coltrane"
:
The operation returns:
The collection now contains the following documents:
Since no documents matched the filter, and upsert
was true
,
updateMany
inserted the document with a
generated _id
, the equality conditions from the filter
, and the
update
modifiers.
Update with Write Concern¶
Given a three member replica set, the following operation specifies a
w
of majority
and wtimeout
of 100
:
If the acknowledgement takes longer than the wtimeout
limit, the following
exception is thrown:
Changed in version 4.4.
The following table explains the possible values of
errInfo.writeConcern.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. |
Specify Collation¶
New in version 3.4.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
A collection myColl
has the following documents:
The following operation includes the collation option:
Specify arrayFilters
for an Array Update Operations¶
New in version 3.6.
Starting in MongoDB 3.6, when updating an array field, you can
specify arrayFilters
that determine which array elements to
update.
Update Elements Match arrayFilters
Criteria¶
Create a collection students
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¶
Create a collection students2
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.1.
Create a sample 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 view the indexes used, you can use the $indexStats
pipeline: