db.collection.updateOne()
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.
New in version 3.2.
Updates a single document within the collection based on the filter.
Syntax
The updateOne()
method has the following syntax:
- db.collection.updateOne(
- <filter>,
- <update>,
- {
- upsert: <boolean>,
- writeConcern: <document>,
- collation: <document>,
- arrayFilters: [ <filterdocument1>, ... ],
- hint: <document|string> // Available starting in MongoDB 4.2.1
- }
- )
Parameters
The db.collection.updateOne()
method takes the followingparameters:
Parameter | Type | Description |
---|---|---|
filter | document | The selection criteria for the update. The same queryselectors as in the find() method are available.Specify an empty document { } to update the first document returned inthe collection. |
update | document | The modifications to apply.The value can be either:- A document that contains update operator expressions, or- Starting in MongoDB 4.2, an aggregation pipeline. The pipeline canconsist of the following stages: - $addFields and its alias $set - $project and its alias $unset - $replaceRoot and its alias $replaceWith .For more information on the update modification parameter, seeUpdate with an Update Operator Expressions Document andUpdate with an Aggregation Pipeline.To update with a replacement document, seedb.collection.replaceOne() . |
upsert | boolean | Optional. When true , updateOne() either:- Creates a new document if no documents match the filter .For more details see upsert behavior.- Updates a single document that matches the filter .To avoid multiple upserts, ensure that the filter fieldsare uniquely indexed.Defaults to false . |
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 ina transaction. To use write concern with transactions, seeTransactions and Write Concern. |
collation | document | Optional.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: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. |
arrayFilters | array | Optional. An array of filter documents that determine which array elements tomodify for an update operation on an array field.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.NoteThe <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 :However, you can specify compound conditions on the same identifierin 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 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.1. |
Returns
The method returns a document that contains:
matchedCount
containing the number of matched documentsmodifiedCount
containing the number of modified documentsupsertedId
containing the_id
for the upserted document.- A boolean
acknowledged
astrue
if the operation ran withwrite concern orfalse
if write concern was disabled
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
Updates a Single Document
db.collection.updateOne()
updates the first matching document inthe collection that matches the filter
, using the update
instructionsto apply modifications.
Update with an Update Operator Expressions Document
For the modification specification, thedb.collection.updateOne()
method can accept a document thatonly contains update operator expressions toperform.
For example:
- db.collection.updateOne(
- <query>,
- { $set: { status: "D" }, $inc: { quantity: 2 } },
- ...
- )
Update with an Aggregation Pipeline
Starting in MongoDB 4.2, the db.collection.updateOne()
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).
For example:
- db.collection.updateOne(
- <query>,
- [
- { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
- { $unset: [ "misc1", "misc2" ] }
- ]
- ...
- )
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
.
For examples, see Update with Aggregation Pipeline.
Upsert
If upsert: true
and no documents match the filter
,db.collection.updateOne()
creates a newdocument based on the filter
criteria and update
modifications. SeeUpdate with Upsert.
If you specify upsert: true
on a sharded collection, you mustinclude the full shard key in the filter. Foradditional db.collection.updateOne()
behavior on a shardedcollection, see Sharded Collections.
Capped Collection
If an update operation changes the document size, the operation will fail.
Sharded Collections
To use db.collection.updateOne()
on a sharded collection:
- If you don’t specify
upsert: true
, you must include an exactmatch on the_id
field or target a single shard (such as byincluding the shard key in the filter). - If you specify
upsert: true
, the filtermust include the shard key.
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.updateOne()
to update the shard key:
- 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.
Explainability
updateOne()
is not compatible withdb.collection.explain()
.
Use update()
instead.
Transactions
db.collection.updateOne()
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.updateOne()
results in anupsert, 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
Update using Update Operator Expressions
The restaurant
collection contains the following documents:
- { "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan" },
- { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
- { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 0 }
The following operation updates a single document wherename: "Central Perk Cafe"
with the violations
field:
- try {
- db.restaurant.updateOne(
- { "name" : "Central Perk Cafe" },
- { $set: { "violations" : 3 } }
- );
- } catch (e) {
- print(e);
- }
The operation returns:
- { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
If no matches were found, the operation instead returns:
- { "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }
Setting upsert: true
would insert the document if no match was found. SeeUpdate with Upsert
Update with Aggregation Pipeline
Starting in MongoDB 4.2, the db.collection.updateOne()
can usean aggregation pipeline for the update. The pipeline can consist of thefollowing 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).
Example 1
The following examples uses the aggregation pipeline to modify a fieldusing 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, comments: [ "reminder: ping me at 100pts", "Some random comment" ] }
- ])
Assume that instead of separate misc1
and misc2
fields in thefirst document, you want to gather these into a comments
field,like the second document. The following update operation uses anaggregation pipeline to add the new comments
field and remove themisc1
and misc2
fields for the specified document.
- db.members.updateOne(
- { _id: 1 },
- [
- { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
- { $unset: [ "misc1", "misc2" ] }
- ]
- )
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" : "A", "points" : 60, "comments" : [ "reminder: ping me at 100pts", "Some random comment" ] }
Example 2
The aggregation pipeline allows the update to perform conditionalupdates based on the current field values as well as use current fieldvalues to calculate a separate field value.
For example, create a students3
collection with the following documents:
- db.students3.insert([
- { "_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 ] }
- ]);
The third document _id: 3
is missing the average
and grade
fields. Using an aggregation pipeline, you can update the document withthe calculated grade average and letter grade.
- db.students3.updateOne(
- { _id: 3 },
- [
- { $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"
- } } } }
- ]
- )
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" }
Update with Upsert
The restaurant
collection contains the following documents:
- { "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
- { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
- { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : "0" }
The following operation attempts to update the document withname : "Pizza Rat's Pizzaria"
, while upsert: true
:
- try {
- db.restaurant.updateOne(
- { "name" : "Pizza Rat's Pizzaria" },
- { $set: {"_id" : 4, "violations" : 7, "borough" : "Manhattan" } },
- { upsert: true }
- );
- } catch (e) {
- print(e);
- }
Since upsert:true
the document is inserted
based on the filter
andupdate
criteria. The operation returns:
- {
- "acknowledged" : true,
- "matchedCount" : 0,
- "modifiedCount" : 0,
- "upsertedId" : 4
- }
The collection now contains the following documents:
- { "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
- { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
- { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 4 },
- { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "violations" : 7 }
The name
field was filled in using the filter
criteria, while theupdate
operators were used to create the rest of the document.
The following operation updates the first document with violations
thatare greater than 10
:
- try {
- db.restaurant.updateOne(
- { "violations" : { $gt: 10} },
- { $set: { "Closed" : true } },
- { upsert: true }
- );
- } catch (e) {
- print(e);
- }
The operation returns:
- {
- "acknowledged" : true,
- "matchedCount" : 0,
- "modifiedCount" : 0,
- "upsertedId" : ObjectId("56310c3c0c5cbb6031cafaea")
- }
The collection now contains the following documents:
- { "_id" : 1, "name" : "Central Perk Cafe", "Borough" : "Manhattan", "violations" : 3 },
- { "_id" : 2, "name" : "Rock A Feller Bar and Grill", "Borough" : "Queens", "violations" : 2 },
- { "_id" : 3, "name" : "Empire State Pub", "Borough" : "Brooklyn", "violations" : 4 },
- { "_id" : 4, "name" : "Pizza Rat's Pizzaria", "Borough" : "Manhattan", "grade" : 7 }
- { "_id" : ObjectId("56310c3c0c5cbb6031cafaea"), "Closed" : true }
Since no documents matched the filter, and upsert
was true
,updateOne
inserted the document with a generated_id
and the update
criteria only.
Update with Write Concern
Given a three member replica set, the following operation specifies aw
of majority
, wtimeout
of 100
:
- try {
- db.restaurant.updateOne(
- { "name" : "Pizza Rat's Pizzaria" },
- { $inc: { "violations" : 3}, $set: { "Closed" : true } },
- { w: "majority", wtimeout: 100 }
- );
- } catch (e) {
- print(e);
- }
If the primary and at least one secondary acknowledge each write operationwithin 100 milliseconds, it returns:
- { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
If the acknowledgement takes longer than the wtimeout
limit, the followingexception is thrown:
- WriteConcernError({
- "code" : 64,
- "errInfo" : {
- "wtimeout" : true
- },
- "errmsg" : "waiting for replication timed out"
- }) :
Specify Collation
New in version 3.4.
Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.
A collection myColl
has the following documents:
- { _id: 1, category: "café", status: "A" }
- { _id: 2, category: "cafe", status: "a" }
- { _id: 3, category: "cafE", status: "a" }
The following operation includes the collationoption:
- db.myColl.updateOne(
- { category: "cafe" },
- { $set: { status: "Updated" } },
- { collation: { locale: "fr", strength: 1 } }
- );
Specify arrayFilters for an Array Update Operations
New in version 3.6.
Starting in MongoDB 3.6, when updating an array field, you canspecify arrayFilters
that determine which array elements toupdate.
Update Elements Match arrayFilters Criteria
Create a collection students
with the following documents:
- db.students.insert([
- { "_id" : 1, "grades" : [ 95, 92, 90 ] },
- { "_id" : 2, "grades" : [ 98, 100, 102 ] },
- { "_id" : 3, "grades" : [ 95, 110, 100 ] }
- ])
To modify all elements that are greater than or equal to 100
in thegrades
array, use the filtered positional operator$[<identifier>]
with the arrayFilters
option in thedb.collection.updateOne
method:
- db.students.updateOne(
- { grades: { $gte: 100 } },
- { $set: { "grades.$[element]" : 100 } },
- { arrayFilters: [ { "element": { $gte: 100 } } ] }
- )
The operation updates the grades
field of a single document, andafter the operation, the collection has the following documents:
- { "_id" : 1, "grades" : [ 95, 92, 90 ] }
- { "_id" : 2, "grades" : [ 98, 100, 100 ] }
- { "_id" : 3, "grades" : [ 95, 110, 100 ] }
Update Specific Elements of an Array of Documents
Create a collection students2
with the following documents:
- db.students2.insert([
- {
- "_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
in the db.collection.updateOne
method:
- db.students2.updateOne(
- { },
- { $set: { "grades.$[elem].mean" : 100 } },
- { arrayFilters: [ { "elem.grade": { $gte: 85 } } ] }
- )
The operation updates the array of a single document, and after theoperation, 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" : 75, "std" : 6 },
- { "grade" : 87, "mean" : 90, "std" : 3 },
- { "grade" : 85, "mean" : 85, "std" : 4 }
- ]
- }
Specify hint for Update Operations
New in version 4.2.1.
Create a sample 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 to use the index {status: 1 }
:
Note
If you specify an index that does not exist, the operation errors.
- db.members.updateOne(
- { "points": { $lte: 20 }, "status": "P" },
- { $set: { "misc1": "Need to activate" } },
- { hint: { status: 1 } }
- )
The update command returns the following:
- { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
To view the indexes used, you can use the $indexStats
pipeline:
- db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )
See also
To update multiple documents, seedb.collection.updateMany()
.