添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Docs Menu

db.collection.update()

Important

Deprecated mongosh Method

This method is deprecated in mongosh . For alternative methods, see Compatibility Changes with Legacy mongo Shell .

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.

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

To learn how to update documents hosted in MongoDB Atlas by using the Atlas UI, see Edit One Document .

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
}
)

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 find() method are available.

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 .

document or pipeline

The modifications to apply. Can be one of the following:

Contains only <field1>: <value1> pairs.

Contains only the following aggregation stages:

For details and examples, see Oplog Entries .

boolean

Optional. When true , update() either:

  • Creates a new document if no documents match the query . For more details see upsert behavior .

  • Updates a single document that matches the query .

If both upsert and multi are true and no documents match the query, the update operation inserts only a single document.

To avoid multiple upserts , ensure that the query field(s) are uniquely indexed . See Upsert with Duplicate Values for an example.

Defaults to false , which does not insert a new document when no match is found.

boolean

Optional. If set to true , updates multiple documents that meet the query criteria. If set to false , updates one document. The default value is false . For additional information, see Update Multiple Documents Examples .

document

Optional. A document expressing the write concern . Omit to use the default write concern w: "majority" .

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 writeConcern , see Override Default Write Concern .

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 collation , see Specify Collation .

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 $[<identifier>] to define an identifier to update only those array elements that match the corresponding filter document in the arrayFilters .

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 .

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 .

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:

{
<variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n>
}

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 ( $$ ) together with your variable name in the form $$<variable_name> . For example: $$targetTotal .

To use a variable to filter results, you must access the variable within the $expr operator.

For a complete example using let and variables, see Use Variables in let .

New in version 5.0 .

The method returns a WriteResult document that contains the status of the operation.

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.

Attempting to use the $expr operator with the upsert flag set to true will generate an error.

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.

Tip

See also:

findAndModify()

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.

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

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() :

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 .

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
  • Can specify multi: true .

  • Requires equality filter on the full shard key if upsert: true .

To set to a non- null value
  • Must be performed either inside a transaction or as a retryable write .

  • Must specify multi: false .

  • Requires equality filter on the full shard key if either:

    • upsert: true , or

    • if using a replacement document and the new shard key value belongs to a different shard.

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:

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 .

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.

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 .

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.

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
}
]);

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 })

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