db.collection.update()
Definition
mongo
Shell Method
This page documents the mongo
shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.
Modifies an existing document or documents in a collection. Themethod can modify specific fields of an existing document or documentsor replace an existing document entirely, depending on theupdate parameter.
By default, the db.collection.update()
method updates asingle document. Include the option multi: trueto update all documents that match the query criteria.
Syntax
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> // Available starting in MongoDB 4.2
- }
- )
Parameters
The db.collection.update()
method takes the followingparameters:
Parameter | Type | Description | ||||||
---|---|---|---|---|---|---|---|---|
query | document | The selection criteria for the update. The same queryselectors as in the find() method are available.Changed in version 3.0: When you execute an update() with upsert:true and the query matches no existing document, MongoDB will refuseto insert a new document if the query specifies conditions on the_id field using dot notation. | ||||||
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 true , creates a new document when nodocument matches the query criteria. The default value isfalse , which does not insert a new document when no matchis found. | ||||||
multi | boolean | Optional. If set to true , updates multiple documents thatmeet the query criteria. If set to false , updates onedocument. The default value is false . For additionalinformation, see Update Multiple Documents Examples. | ||||||
writeConcern | document | Optional. A document expressing the write concern. Omit to use the default writeconcern w: 1 .
Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern. For an example using | ||||||
collation | document | Optional.
Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks. For an example using New in version 3.4. | ||||||
arrayFilters | array | Optional. An array of filter documents that determine which arrayelements 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 ifthe 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 indexname string. If you specify an index that does not exist, the operationerrors. For an example, see Specify hint for Update Operations. New in version 4.2. |
Returns
The method returns a WriteResult document that containsthe status of the operation.
Access Control
On deployments running with authorization
, theuser 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 theoperation results in an upsert.
The built-in role readWrite
provides the requiredprivileges.
Behavior
Sharded Collections
To use db.collection.update()
with multi: false
on asharded 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 targeta single shard, first by using the query filter. If the operationcannot target a single shard by the query filter, it then attempts to targetby the replacement document.
In earlier versions, the operation attempts to target using thereplacement document.
upsert on a Sharded Collection
For a db.collection.update()
operation that includesupsert: true and is on a sharded collection, youmust include the full shard key in the filter
:
- For an update operation.
- For a replace document operation (starting in MongoDB 4.2).
Shard Key Modification
Starting in MongoDB 4.2, you can update a document’s shard key valueunless the shard key field is the immutable _id
field. For detailson updating the shard key, see Change a Document’s Shard Key Value.
Before MongoDB 4.2, a document’s shard key field value is immutable.
To use db.collection.update()
to update the shard key:
- You must specify
multi: false
.
- You must run on a
mongos
either in atransaction or as a retryablewrite. Do not issue the operationdirectly on the shard. - You must include an equality condition on the full shardkey in the query filter. For example, if a collection
messages
uses{ country : 1, userid : 1 }
as the shard key, to updatethe shard key for a document, you must includecountry: <value>,userid: <value>
in the query filter. You can include additionalfields in the query as appropriate.
Transactions
db.collection.update()
can be used inside multi-document transactions.
Important
In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.
For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.
Existing Collections and Transactions
Inside a transaction, you can specify read/write operations on existingcollections. If the db.collection.update()
results in anupsert, the collection must already exist.
If the operation results in an upsert, the collection must already exist.
Write Concerns and Transactions
Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions 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 whichcontains the following documents. This command first removes allpreviously 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
- }
- ]);
If the <update>
document contains update operator modifiers, such as those using the$set
modifier, then:
- The
<update>
document must contain onlyupdate operator expressions. - The
db.collection.update()
method updates only thecorresponding 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 inan array, use dot notationto specify the field.
You can use the web shell below to insert the sampledocuments and execute the example update operation:
- db.books.update(
- { _id: 1 },
- {
- $inc: { stock: 5 },
- $set: {
- item: "ABC123",
- "info.publisher": "2222",
- tags: [ "software" ],
- "ratings.1": { by: "xyz", rating: 3 }
- }
- }
- )
In this operation:
- The
<query>
parameter of{ _id: 1 }
specifies whichdocument 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:
- {
- "_id" : 1,
- "item" : "ABC123",
- "stock" : 5,
- "info" : { "publisher" : "2222", "pages" : 430 },
- "tags" : [ "software" ],
- "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
- "reorder" : false
- }
This operation corresponds to the following SQL statement:
- UPDATE books
- SET stock = stock + 5
- item = "ABC123"
- publisher = 2222
- pages = 430
- tags = "software"
- rating_authors = "ijk,xyz"
- rating_values = "4,3"
- WHERE _id = 1
Note
If the query
parameter had matched multiple documents,this operation would only update one matching document. Toupdate multiple documents, you must set the multi
optionto true
.
See also
$set
, $inc
,Update Operators,dot notation
From the mongo
shell, create a books
collection whichcontains the following documents. This command first removes allpreviously 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
- }
- ]);
The following operation uses the $push
updateoperator to append a new object to the ratings
array.
You can use the web shell below to insert the sampledocuments and execute the example update operation:
- db.books.update(
- { _id: 2 },
- {
- $push: { ratings: { "by" : "jkl", "rating" : 2 } }
- }
- )
The updated document is the following:
- {
- "_id" : 2,
- "item" : "XYZ123",
- "stock" : 15,
- "info" : {
- "publisher" : "5555",
- "pages" : 150
- },
- "tags" : [ ],
- "ratings" : [
- { "by" : "xyz", "rating" : 5 },
- { "by" : "jkl", "rating" : 2 }
- ],
- "reorder" : false
- }
See also
From the mongo
shell, create a books
collection whichcontains the following documents. This command first removes allpreviously 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
- }
- ]);
The following operation uses the $unset
operator to removethe tags
field from the document with { _id: 1 }
.
You can use the web shell below to insert the sampledocuments and execute the example update operation:
- db.books.update( { _id: 1 }, { $unset: { tags: 1 } } )
The updated document is the following:
- {
- "_id" : 1,
- "item" : "TBD",
- "stock" : 0,
- "info" : {
- "publisher" : "1111",
- "pages" : 430
- },
- "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "lmn", "rating" : 5 } ],
- "reorder" : false
- }
There is not a direct SQL equivalent to $unset
,however $unset
is similar to the following SQLcommand which removes the tags
field from the books
table:
- ALTER TABLE books
- DROP COLUMN tags
See also
$unset
, $rename
, Update Operators
From the mongo
shell, create a books
collection whichcontains the following documents. This command first removes allpreviously 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
- }
- ]);
If the <update>
document contains only field:value
expressions, then:
- The
db.collection.update()
method replaces the matchingdocument with the<update>
document. Thedb.collection.update()
method does not replace the_id
value. db.collection.update()
cannot update multipledocuments.
The following operation passes an <update>
document that containsonly field and value pairs. The <update>
document completelyreplaces the original document except for the _id
field.
You can use the web shell below to insert the sampledocuments and execute the example update operation:
- db.books.update(
- { _id: 2 },
- {
- item: "XYZ123",
- stock: 10,
- info: { publisher: "2255", pages: 150 },
- tags: [ "baking", "cooking" ]
- }
- )
The updated document contains only the fields from thereplacement document and the _id
field. As such, the fieldsratings
and reorder
no longer exist in the updateddocument since the fields were not in the replacement document.
- {
- "_id" : 2,
- "item" : "XYZ123",
- "stock" : 10,
- "info" : { "publisher" : "2255", "pages" : 150 },
- "tags" : [ "baking", "cooking" ]
- }
This operation corresponds to the following SQL statements:
- DELETE from books WHERE _id = 2
- INSERT INTO books
- (_id,
- item,
- stock,
- publisher,
- pages,
- tags)
- VALUES (2,
- "xyz123",
- 10,
- "2255",
- 150,
- "baking,cooking")
From the mongo
shell, create a books
collection whichcontains the following documents. This command first removes allpreviously 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
- }
- ]);
If multi
is set to true
, thedb.collection.update()
method updates all documentsthat meet the <query>
criteria. The multi
updateoperation 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 to10
. If the reorder
field does not exist in the matchingdocument(s), the $set
operator adds the fieldwith the specified value.
You can use the web shell below to insert the sampledocuments and execute the example update operation:
- db.books.update(
- { stock: { $lte: 10 } },
- { $set: { reorder: true } },
- { multi: true }
- )
The resulting documents in the collection are the following:
- [
- {
- "_id" : 1,
- "item" : "ABC123",
- "stock" : 5,
- "info" : {
- "publisher" : "2222",
- "pages" : 430
- },
- "ratings" : [ { "by" : "ijk", "rating" : 4 }, { "by" : "xyz", "rating" : 3 } ],
- "reorder" : true
- }
- {
- "_id" : 2,
- "item" : "XYZ123",
- "stock" : 10,
- "info" : { "publisher" : "2255", "pages" : 150 },
- "tags" : [ "baking", "cooking" ],
- "reorder" : true
- }
- ]
This operation corresponds to the following SQL statement:
- UPDATE books
- SET reorder=true
- WHERE stock <= 10
Note
You cannot specify multi: true
when performing areplacement, i.e., when the <update> document contains onlyfield: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 mustinclude the full shard key in the filter
. For additionaldb.collection.update()
behavior on a sharded collection, seeSharded 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 fieldand value pairs), the update inserts a new document with thefields and values of the replacement document.
If you specify an
_id
field in either the query parameteror replacement document, MongoDB uses that_id
field in theinserted document.If you do not specify an
_id
field in either the queryparameter or replacement document, MongoDB generates adds the_id
field with a randomly generated ObjectIdvalue.
Note
You cannot specify different _id
field values in thequery parameter and replacement document. If you do, theoperation errors.
For example, the following update sets the upsert option to true
:
- db.books.update(
- { item: "ZZZ135" }, // Query parameter
- { // Replacement document
- item: "ZZZ135",
- stock: 5,
- tags: [ "database" ]
- },
- { upsert: true } // Options
- )
If no document matches the <query>
parameter, the updateoperation inserts a document with only the replacementdocument. Because no _id
field was specified in thereplacement document or query document, the operation creates anew unique ObjectId
for the new document’s _id
field.You can see the upsert
reflected in the WriteResult of the operation:
- WriteResult({
- "nMatched" : 0,
- "nUpserted" : 1,
- "nModified" : 0,
- "_id" : ObjectId("5da78973835b2f1c75347a83")
- })
The operation inserts the following document into the books
collection (your ObjectId value will differ):
- {
- "_id" : ObjectId("5da78973835b2f1c75347a83"),
- "item" : "ZZZ135",
- "stock" : 5,
- "tags" : [ "database" ]
- }
If no document matches the query criteria and the <update>
parameter is a document with update operator expressions, then the operation creates a base documentfrom the equality clauses in the <query>
parameter andapplies the expressions from the <update>
parameter.
Comparison operations fromthe <query>
will not be included in the new document. Ifthe new document does not include the _id
field, MongoDBadds the _id
field with an ObjectId value.
For example, the following update sets the upsert option to true
:
- db.books.update(
- { item: "BLP921" }, // Query parameter
- { // Update document
- $set: { reorder: false },
- $setOnInsert: { stock: 10 }
- },
- { upsert: true } // Options
- )
If no documents match the query condition, the operationinserts the following document (your ObjectId valuewill differ):
- {
- "_id" : ObjectId("5da79019835b2f1c75348a0a"),
- "item" : "BLP921",
- "reorder" : false,
- "stock" : 10
- }
See also
If the <update>
parameter is an aggregation pipeline, the update creates a basedocument from the equality clauses in the <query>
parameter, and then applies the pipeline to the document tocreate the document to insert. If the new document does notinclude the _id
field, MongoDB adds the _id
field withan ObjectId value.
For example, the following update sets theupsert option to true
:
- db.books.update(
- { // Query parameter
- item: "MRQ014",
- ratings: [2, 5, 3]
- },
- [ // Aggregation pipeline
- { // Update document
- $set: {
- "tags": [ "fiction", "hardcover" ],
- "averageRating": { $avg: "$ratings" }
- }
- }
- ],
- { upsert: true } // Options
- )
If no document matches the <query>
parameter, theoperation inserts the following document into the books
collection (your ObjectId value will differ):
- {
- "_id" : ObjectId("5da7991c835b2f1c75349ed9"),
- "item" : "MRQ014",
- "ratings" : [ 2, 5, 3 ],
- "tags" : [ "fiction", "hardcover" ],
- "averageRating" : 3.3333333333333335
- }
See also
For additional examples of updates usingaggregation pipelines, see Update with Aggregation Pipeline.
Combine Upsert and Multi Options (Match)
From the mongo
shell, insert the followingdocuments into a books
collection:
- db.books.insertMany([
- {
- _id: 5,
- item: "RQM909",
- stock: 18,
- info: { publisher: "0000", pages: 170 },
- reorder: true
- },
- {
- _id: 6,
- item: "EFG222",
- stock: 15,
- info: { publisher: "1111", pages: 72 },
- reorder: true
- }
- ])
The following operation specifies both the multi
option andthe upsert
option. If matching documents exist, theoperation updates all matching documents. If no matchingdocuments exist, the operation inserts a new document.
- db.books.update(
- { stock: { $gte: 10 } }, // Query parameter
- { // Update document
- $set: { reorder: false, tags: [ "literature", "translated" ] }
- },
- { upsert: true, multi: true } // Options
- )
The operation updates all matching documents and results in thefollowing:
- {
- "_id" : 5,
- "item" : "RQM909",
- "stock" : 18,
- "info" : { "publisher" : "0000", "pages" : 170 },
- "reorder" : false,
- "tags" : [ "literature", "translated" ]
- }
- {
- "_id" : 6,
- "item" : "EFG222",
- "stock" : 15,
- "info" : { "publisher" : "1111", "pages" : 72 },
- "reorder" : false,
- "tags" : [ "literature", "translated" ]
- }
Combine Upsert and Multi Options (No Match)
If the collection had no matching document, the operationwould result in the insertion of a single document using thefields from both the <query>
and the <update>
specifications. For example, consider the following operation:
- db.books.update(
- { "info.publisher": "Self-Published" }, // Query parameter
- { // Update document
- $set: { reorder: false, tags: [ "literature", "hardcover" ], stock: 25 }
- },
- { upsert: true, multi: true } // Options
- )
The operation inserts the following document into the books
collection (your ObjectId value will differ):
- {
- "_id" : ObjectId("5db337934f670d584b6ca8e0"),
- "info" : { "publisher" : "Self-Published" },
- "reorder" : false,
- "stock" : 25,
- "tags" : [ "literature", "hardcover" ]
- }
When you execute an update()
with upsert:true
and the query matches no existing document, MongoDB will refuseto 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 inthe query.
If you attempt to insert a document in this way, MongoDB will raise anerror. For example, consider the following update operation. Since theupdate operation specifies upsert:true
and the query specifiesconditions on the _id
field using dot notation, then the update willresult in an error when constructing the document to insert.
- db.collection.update( { "_id.name": "Robert Frost", "_id.uid": 0 },
- { "categories": ["poet", "playwright"] },
- { upsert: true } )
The WriteResult
of the operation returns the followingerror:
- WriteResult({
- "nMatched" : 0,
- "nUpserted" : 0,
- "nModified" : 0,
- "writeError" : {
- "code" : 111,
- "errmsg" : "field at '_id' must be exactly specified, field at sub-path '_id.name'found"
- }
- })
See also
Use Unique Indexes
Warning
To avoid inserting the same document more than once,only use upsert: true
if the query
field is uniquelyindexed.
Given a collection named people
where no documents havea name
field that holds the value Andy
, consider when multipleclients issue the following db.collection.update()
withupsert: true
at the same time:
- db.people.update(
- { name: "Andy" }, // Query parameter
- { // Update document
- name: "Andy",
- rating: 1,
- score: 1
- },
- { upsert: true } // Options
- )
If all db.collection.update()
operations complete thequery
portion before any client successfully inserts data, andthere is no unique index on the name
field, then each updateoperation 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 updatewith upsert: true
, exactly onedb.collection.update()
would successfully insert a newdocument.
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 updateoperation.
See also
Update with Aggregation Pipeline
Starting in MongoDB 4.2, the db.collection.update()
methodcan accept an aggregation pipeline [ <stage1>, <stage2>, … ]
thatspecifies the modifications to perform. The pipeline can consist ofthe 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 updatestatement, such as expressing conditional updates based on currentfield 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:
- db.members.insertMany([
- { "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" },
- { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
- ])
Assume that instead of separate misc1
and misc2
fields, youwant to gather these into a new comments
field. The followingupdate operation uses an aggregation pipeline to add the newcomments
field and remove the misc1
and misc2
fields forall documents in the collection.
- db.members.update(
- { },
- [
- { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
- { $unset: [ "misc1", "misc2" ] }
- ],
- { multi: true }
- )
Note
The $set
and $unset
used in the pipeline refers to theaggregation stages $set
and $unset
respectively, and not the update operators $set
and$unset
.
- First Stage
- The
$set
stage creates a new array fieldcomments
whose elements are the current content of themisc1
andmisc2
fields. - Second Stage
- The
$unset
stage removes themisc1
andmisc2
fields.
After the command, the collection contains the following documents:
- { "_id" : 1, "member" : "abc123", "status" : "Modified", "points" : 2, "comments" : [ "note to self: confirm status", "Need to activate" ] }
- { "_id" : 2, "member" : "xyz123", "status" : "Modified", "points" : 60, "comments" : [ "reminder: ping me at 100pts", "Some random comment" ] }
Perform Conditional Updates Based on Current Field Values
Create a students3
collection with the following documents:
- db.students3.insert([
- { "_id" : 1, "tests" : [ 95, 92, 90 ] },
- { "_id" : 2, "tests" : [ 94, 88, 90 ] },
- { "_id" : 3, "tests" : [ 70, 75, 82 ] }
- ]);
Using an aggregation pipeline, you can update the documents with thecalculated grade average and letter grade.
- db.students3.update(
- { },
- [
- { $set: { average : { $avg: "$tests" } } },
- { $set: { grade: { $switch: {
- branches: [
- { case: { $gte: [ "$average", 90 ] }, then: "A" },
- { case: { $gte: [ "$average", 80 ] }, then: "B" },
- { case: { $gte: [ "$average", 70 ] }, then: "C" },
- { case: { $gte: [ "$average", 60 ] }, then: "D" }
- ],
- default: "F"
- } } } }
- ],
- { multi: true }
- )
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 fieldaverage
basedon the average of thetests
field. See$avg
formore information on the$avg
aggregation operator. - Second Stage
- The
$set
stage calculates a new fieldgrade
based ontheaverage
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:
- { "_id" : 1, "tests" : [ 95, 92, 90 ], "average" : 92.33333333333333, "grade" : "A" }
- { "_id" : 2, "tests" : [ 94, 88, 90 ], "average" : 90.66666666666667, "grade" : "A" }
- { "_id" : 3, "tests" : [ 70, 75, 82 ], "average" : 75.66666666666667, "grade" : "C" }
Specify arrayFilters for Array Update Operations
In the update document, use the $[<identifier>]
filteredpositional operator to define an identifier, which you then referencein the array filter documents. You cannot have an array filterdocument for an identifier if the identifier is not included in theupdate document.
Note
The <identifier>
must begin with a lowercase letter andcontain only alphanumeric characters.
You can include the same identifier multiple times in the updatedocument; however, for each distinct identifier ($[identifier]
)in the update document, you must specify exactly onecorresponding array filter document. That is, you cannot specifymultiple array filter documents for the same identifier. Forexample, if the update statement includes the identifier x
(possibly multiple times), you cannot specify the following forarrayFilters
that includes 2 separate filter documents for x
:
- // INVALID
- [
- { "x.a": { $gt: 85 } },
- { "x.b": { $gt: 80 } }
- ]
However, you can specify compound conditions on the same identifierin a single filter document, such as in the following examples:
- // Example 1
- [
- { $or: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }
- ]
- // Example 2
- [
- { $and: [{"x.a": {$gt: 85}}, {"x.b": {$gt: 80}}] }
- ]
- // Example 3
- [
- { "x.a": { $gt: 85 }, "x.b": { $gt: 80 } }
- ]
arrayFilters
is not available for updates that use anaggregation pipeline.
Update Elements Match arrayFilters Criteria
To update all array elements which match a specified criteria, use thearrayFilters parameter.
From the mongo
shell, create a students
collection with the following documents:
- db.students.insertMany([
- { "_id" : 1, "grades" : [ 95, 92, 90 ] },
- { "_id" : 2, "grades" : [ 98, 100, 102 ] },
- { "_id" : 3, "grades" : [ 95, 110, 100 ] }
- ])
To update all elements that are greater than or equal to 100
in thegrades
array, use the filtered positional operator$[<identifier>]
with the arrayFilters
option:
- db.students.update(
- { grades: { $gte: 100 } },
- { $set: { "grades.$[element]" : 100 } },
- {
- multi: true,
- arrayFilters: [ { "element": { $gte: 100 } } ]
- }
- )
After the operation, the collection contains the following documents:
- { "_id" : 1, "grades" : [ 95, 92, 90 ] }
- { "_id" : 2, "grades" : [ 98, 100, 100 ] }
- { "_id" : 3, "grades" : [ 95, 100, 100 ] }
Update Specific Elements of an Array of Documents
You can also use the arrayFiltersparameter to update specific document fields within an array ofdocuments.
From the mongo
shell, create a students2
collection with the following documents:
- db.students2.insertMany([
- {
- "_id" : 1,
- "grades" : [
- { "grade" : 80, "mean" : 75, "std" : 6 },
- { "grade" : 85, "mean" : 90, "std" : 4 },
- { "grade" : 85, "mean" : 85, "std" : 6 }
- ]
- }
- {
- "_id" : 2,
- "grades" : [
- { "grade" : 90, "mean" : 75, "std" : 6 },
- { "grade" : 87, "mean" : 90, "std" : 3 },
- { "grade" : 85, "mean" : 85, "std" : 4 }
- ]
- }
- ])
To modify the value of the mean
field for all elements in thegrades
array where the grade is greater than or equal to 85
,use the filtered positional operator $[<identifier>]
withthe arrayFilters
:
- db.students2.update(
- { },
- { $set: { "grades.$[elem].mean" : 100 } },
- {
- multi: true,
- arrayFilters: [ { "elem.grade": { $gte: 85 } } ]
- }
- )
After the operation, the collection has the following documents:
- {
- "_id" : 1,
- "grades" : [
- { "grade" : 80, "mean" : 75, "std" : 6 },
- { "grade" : 85, "mean" : 100, "std" : 4 },
- { "grade" : 85, "mean" : 100, "std" : 6 }
- ]
- }
- {
- "_id" : 2,
- "grades" : [
- { "grade" : 90, "mean" : 100, "std" : 6 },
- { "grade" : 87, "mean" : 100, "std" : 3 },
- { "grade" : 85, "mean" : 100, "std" : 4 }
- ]
- }
Specify hint for Update Operations
New in version 4.2.
From the mongo
shell, create a members
collection with the following documents:
- db.members.insertMany([
- { "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
- { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
- { "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
- { "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null },
- { "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
- { "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
- ])
Create the following indexes on the collection:
- db.members.createIndex( { status: 1 } )
- db.members.createIndex( { points: 1 } )
The following update operation explicitly hints touse the index {status: 1 }
:
Note
If you specify an index that does not exist, the operation errors.
- db.members.update(
- { points: { $lte: 20 }, status: "P" }, // Query parameter
- { $set: { misc1: "Need to activate" } }, // Update document
- { multi: true, hint: { status: 1 } } // Options
- )
The update command returns the following:
- WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
To see the index used, run explain
on the operation:
- db.members.explain().update(
- { "points": { $lte: 20 }, "status": "P" },
- { $set: { "misc1": "Need to activate" } },
- { multi: true, hint: { status: 1 } }
- )
The db.collection.explain().update()
does not modify the documents.
Override Default Write Concern
The following operation on a replica set specifies a writeconcern of "w: majority"
with awtimeout
of 5000 milliseconds such that the method returns afterthe write propagates to a majority of the voting replica set members orthe method times out after 5 seconds.
Changed in version 3.0: In previous versions, majority
referred to the majority of allmembers of the replica set instead of the majority of the votingmembers.
- db.books.update(
- { stock: { $lte: 10 } },
- { $set: { reorder: true } },
- {
- multi: true,
- writeConcern: { w: "majority", wtimeout: 5000 }
- }
- )
Specify Collation
Specifies the collation to use for the operation.
Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.
The collation option has the following syntax:
- collation: {
- locale: <string>,
- caseLevel: <boolean>,
- caseFirst: <string>,
- strength: <int>,
- numericOrdering: <boolean>,
- alternate: <string>,
- maxVariable: <string>,
- backwards: <boolean>
- }
When specifying collation, the locale
field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.
If the collation is unspecified but the collection has adefault collation (see db.createCollection()
), theoperation uses the collation specified for the collection.
If no collation is specified for the collection or for theoperations, MongoDB uses the simple binary comparison used in priorversions for string comparisons.
You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.
New in version 3.4.
From the mongo
shell, create a collection namedmyColl
with the following documents:
- db.myColl.insertMany(
- [
- { _id: 1, category: "café", status: "A" },
- { _id: 2, category: "cafe", status: "a" },
- { _id: 3, category: "cafE", status: "a" }
- ])
The following operation includes the collationoption and sets multi
to true
to update all matching documents:
- db.myColl.update(
- { category: "cafe" },
- { $set: { status: "Updated" } },
- {
- collation: { locale: "fr", strength: 1 },
- multi: true
- }
- );
The write result of the operation returns the following document, indicating that all three documents in thecollection were updated:
- WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
After the operation, the collection contains the following documents:
- { "_id" : 1, "category" : "café", "status" : "Updated" }
- { "_id" : 2, "category" : "cafe", "status" : "Updated" }
- { "_id" : 3, "category" : "cafE", "status" : "Updated" }
WriteResult
Changed in version 2.6.
Successful Results
The db.collection.update()
method returns aWriteResult
object that contains the status of the operation.Upon success, the WriteResult
object contains the number ofdocuments that matched the query condition, the number of documentsinserted by the update, and the number of documents modified:
- WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
See
WriteResult.nMatched
, WriteResult.nUpserted
,WriteResult.nModified
Write Concern Errors
If the db.collection.update()
method encounters writeconcern errors, the results include theWriteResult.writeConcernError
field:
- WriteResult({
- "nMatched" : 1,
- "nUpserted" : 0,
- "nModified" : 1,
- "writeConcernError" : {
- "code" : 64,
- "errmsg" : "waiting for replication timed out at shard-a"
- }
- })
See also
WriteResult.hasWriteConcernError()
Errors Unrelated to Write Concern
If the db.collection.update()
method encounters a non-writeconcern error, the results include the WriteResult.writeError
field:
- WriteResult({
- "nMatched" : 0,
- "nUpserted" : 0,
- "nModified" : 0,
- "writeError" : {
- "code" : 7,
- "errmsg" : "could not contact primary for replica set shard-a"
- }
- })
See also