update

Definition

  • update
  • The update command modifies documents in a collection.A single update command can contain multiple updatestatements. The update methods provided by the MongoDB drivers usethis command internally.

The mongo shell provides the following helper methods:

Syntax

Changed in version 4.2.

The update command has the following syntax:

  1. db.runCommand(
  2. {
  3. update: <collection>,
  4. updates: [
  5. {
  6. q: <query>,
  7. u: <document or pipeline>, // Changed in MongoDB 4.2,
  8. upsert: <boolean>,
  9. multi: <boolean>,
  10. collation: <document>,
  11. arrayFilters: <array>,
  12. hint: <document|string> // Available starting in MongoDB 4.2
  13. },
  14. ...
  15. ],
  16. ordered: <boolean>,
  17. writeConcern: { <write concern> },
  18. bypassDocumentValidation: <boolean>
  19. }
  20. )

Command Fields

The command takes the following fields:

FieldTypeDescription
updatestringThe name of the target collection.
updatesarrayAn array of one or more update statements to perform on the namedcollection. For details of the update statements, see UpdateStatements.
orderedbooleanOptional. If true, then when an update statement fails, return withoutperforming the remaining update statements. If false, then whenan update fails, continue with the remaining update statements, ifany. Defaults to true.
writeConcerndocumentOptional. A document expressing the write concernof the update command. Omit to use the default writeconcern.Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.
bypassDocumentValidationbooleanOptional. Enables update to bypass document validationduring the operation. This lets you update documents that do notmeet the validation requirements.New in version 3.2.

Update Statements

Each element of the updates array is an update statement document.Each document contains the following fields:

FieldTypeDescription
qdocumentThe query that matches documents to update. Use the same queryselectors as used in the find() method.
udocument or pipelineThe modifications to apply.The value can be either:- A document that contains update operator expressions,- A replacement document with only <field1>: <value1> pairs, or- Starting in MongoDB 4.2, an aggregation pipeline. - $addFields and its alias $set - $project and its alias $unset - $replaceRoot and its alias $replaceWith.For details, see Behavior.
upsertbooleanOptional. If true, perform an insert if no documents match the query. Ifboth upsert and multi are true and no documents match thequery, the update operation inserts only a single document.
multibooleanOptional. If true, updates all documents that meet the query criteria. Iffalse, limit the update to one document that meet the querycriteria. Defaults to false.
collationdocumentOptional.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:
  1. 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.
arrayFiltersarrayOptional. An array of filter documents that determines 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:
  1. // 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:
  1. // 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 } }]
For examples, see Specify arrayFilters for Array Update Operations.New in version 3.6.
hintDocument or stringOptional. 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 command returns a document that contains the status of theoperation. For example:

  1. {
  2. "ok" : 1,
  3. "nModified" : 0,
  4. "n" : 1,
  5. "upserted" : [
  6. {
  7. "index" : 0,
  8. "_id" : ObjectId("52ccb2118908ccd753d65882")
  9. }
  10. ]
  11. }

For details of the output fields, see Output.

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

The built-in role readWrite provides the requiredprivileges.

Behavior

Update with an Update Operator Expressions Document

The update statement field u can accept adocument that only contains update operatorexpressions. For example:

  1. updates: [
  2. {
  3. q: <query>,
  4. u: { $set: { status: "D" }, $inc: { quantity: 2 } },
  5. ...
  6. },
  7. ...
  8. ]

Then, the update command updates only the correspondingfields in the document.

Update with a Replacement Document

The update statement field u field can accepta replacement document, i.e. the document contains onlyfield:value expressions. For example:

  1. updates: [
  2. {
  3. q: <query>,
  4. u: { status: "D", quantity: 4 },
  5. ...
  6. },
  7. ...
  8. ]

Then the update command replaces the matching documentwith the update document. The update command can onlyreplace a single matching document; i.e. the multi field cannotbe true. The update command does not replace the_id value.

Update with an Aggregation Pipeline

Starting in MongoDB 4.2, the update statement field u field can accept an aggregation pipeline [ <stage1>, <stage2>, … ] thatspecifies the modifications to perform. The pipeline can consist ofthe following stages:

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:

  1. updates: [
  2. {
  3. q: <query>,
  4. u: [
  5. { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
  6. { $unset: [ "misc1", "misc2" ] }
  7. ],
  8. ...
  9. },
  10. ...
  11. ]

Note

The $set and $unset used in the pipeline refers to theaggregation stages $set and $unsetrespectively, and not the update operators $set and $unset.

For examples, see Update with Aggregation Pipeline.

Limits

For each update element in the updates array, the sum of the queryand the update sizes (i.e. q and u ) must be less than or equalto the maximum BSON document size.

The total number of update statements in the updates array must beless than or equal to the maximum bulk size.

Document Validation

The update command adds support for thebypassDocumentValidation option, which lets you bypassdocument validation wheninserting or updating documents in a collection with validationrules.

Sharded Collections

To use update with multi: false on a shardedcollection,

  • If you do not specify upsert: true,you must include an equality match on the _id field or target asingle shard (such as by including the shard key).
  • If you specify upsert: true, thefilter q must include an equality match on theshard 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 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 messagesuses { country : 1, userid : 1 } as the shard key, to updatethe shard key for a document, you must include country: <value>,userid: <value> in the query filter. You can include additionalfields in the query as appropriate.

Replace Document

Starting in MongoDB 4.2, when replacing a document, update attemptsto target a 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.

Transactions

update can be used inside multi-document transactions.

If the operation results in an upsert, the collection must already exist.

Do not explicitly set the write concern for the operation if run ina transaction. To use write concern with transactions, seeTransactions and Write Concern.

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.

Examples

Update Specific Fields of One Document

Use update operators to update only thespecified fields of a document.

For example, create a members collection with the following documents:

  1. db.members.insertMany([
  2. { _id: 1, member: "abc123", status: "Pending", points: 0, misc1: "note to self: confirm status", misc2: "Need to activate" },
  3. { _id: 2, member: "xyz123", status: "D", points: 59, misc1: "reminder: ping me at 100pts", misc2: "Some random comment" },
  4. ])

The following command uses the $set and $incupdate operators to update the status and the points fields of adocument where the member equals "abc123":

  1. db.runCommand(
  2. {
  3. update: "members",
  4. updates: [
  5. {
  6. q: { member: "abc123" }, u: { $set: { status: "A" }, $inc: { points: 1 } }
  7. }
  8. ],
  9. ordered: false,
  10. writeConcern: { w: "majority", wtimeout: 5000 }
  11. }
  12. )

Because <update> document does not specify the optional multifield, the update only modifies one document, even if more than onedocument matches the q match condition.

The returned document shows that the command found and updated a singledocument. The command returns:

  1. { "n" : 1, "nModified" : 1, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

See Output for details.

After the command, the collection contains the following documents:

  1. { "_id" : 1, "member" : "abc123", "status" : "A", "points" : 1, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
  2. { "_id" : 2, "member" : "xyz123", "status" : "D", "points" : 59, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

Update Specific Fields of Multiple Documents

Use update operators to update only thespecified fields of a document, and include the multi field set totrue in the update statement.

For example, a members collection contains the following documents:

  1. { "_id" : 1, "member" : "abc123", "status" : "A", "points" : 1, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
  2. { "_id" : 2, "member" : "xyz123", "status" : "D", "points" : 59, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

The following command uses the $set and $incupdate operators to modify the status and the points fieldsrespectively of all documents in the collection:

  1. db.runCommand(
  2. {
  3. update: "members",
  4. updates: [
  5. { q: { }, u: { $set: { status: "A" }, $inc: { points: 1 } }, multi: true }
  6. ],
  7. ordered: false,
  8. writeConcern: { w: "majority", wtimeout: 5000 }
  9. }
  10. )

The update modifies all documents that match the query specified in theq field, namely the empty query which matches all documents in thecollection.

The returned document shows that the command found and updated multipledocuments. For a replica set, the command returns:

  1. { "n" : 2, "nModified" : 2, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

See Output for details.

After the command, the collection contains the following documents:

  1. { "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
  2. { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }

Update with Aggregation Pipeline

Starting in MongoDB 4.2, the update command can use anaggregation pipeline for the update. The pipeline can consist of thefollowing stages:

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.

A members collection contains the following documents:

  1. { "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate" }
  2. { "_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.

  • First, set the status field to "Modified" and add a newfield comments that contains the current contents of two otherfields misc1 and misc2 fields.
  • Second, remove the misc1 and misc2 fields.
  1. db.runCommand(
  2. {
  3. update: "members",
  4. updates: [
  5. {
  6. q: { },
  7. u: [
  8. { $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
  9. { $unset: [ "misc1", "misc2" ] }
  10. ],
  11. multi: true
  12. }
  13. ],
  14. ordered: false,
  15. writeConcern: { w: "majority", wtimeout: 5000 }
  16. }
  17. )

Note

The $set and $unset used in the pipeline refers to theaggregation stages $set and $unsetrespectively, and not the update operators $set and $unset.

The returned document shows that the command found and updated multipledocuments. The command returns:

  1. { "n" : 2, "nModified" : 2, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

See Output for details.

After the command, the collection contains the following documents:

  1. { "_id" : 1, "member" : "abc123", "status" : "Modified", "points" : 2, "comments" : [ "note to self: confirm status", "Need to activate" ] }
  2. { "_id" : 2, "member" : "xyz123", "status" : "Modified", "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.

  1. db.students.insert([
  2. { "_id" : 1, "tests" : [ 95, 92, 90 ] },
  3. { "_id" : 2, "tests" : [ 94, 88, 90 ] },
  4. { "_id" : 3, "tests" : [ 70, 75, 82 ] }
  5. ]);

Using an aggregation pipeline, you can update the documents with thecalculated grade average and letter grade.

  1. db.runCommand(
  2. {
  3. update: "students",
  4. updates: [
  5. {
  6. q: { },
  7. u: [
  8. { $set: { average : { $avg: "$tests" } } },
  9. { $set: { grade: { $switch: {
  10. branches: [
  11. { case: { $gte: [ "$average", 90 ] }, then: "A" },
  12. { case: { $gte: [ "$average", 80 ] }, then: "B" },
  13. { case: { $gte: [ "$average", 70 ] }, then: "C" },
  14. { case: { $gte: [ "$average", 60 ] }, then: "D" }
  15. ],
  16. default: "F"
  17. } } } }
  18. ],
  19. multi: true
  20. }
  21. ],
  22. ordered: false,
  23. writeConcern: { w: "majority", wtimeout: 5000 }
  24. }
  25. )

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 basedon the average of the tests field. See $avg formore information on the $avg aggregation operator.
  • Second Stage
  • The $set stage calculates a new field grade based onthe average field calculated in the previous stage. See$switch for more information on the $switchaggregation operator.

The returned document shows that the command found and updated multipledocuments. The command returns:

  1. { "n" : 3, "nModified" : 3, "ok" : 1, <additional fields if run on a replica set/sharded cluster> }

After the command, the collection contains the following documents:

  1. { "_id" : 1, "tests" : [ 95, 92, 90 ], "average" : 92.33333333333333, "grade" : "A" }
  2. { "_id" : 2, "tests" : [ 94, 88, 90 ], "average" : 90.66666666666667, "grade" : "A" }
  3. { "_id" : 3, "tests" : [ 70, 75, 82 ], "average" : 75.66666666666667, "grade" : "C" }

Bulk Update

The following example performs multiple update operations on themembers collection:

  1. db.runCommand(
  2. {
  3. update: "members",
  4. updates: [
  5. { q: { status: "P" }, u: { $set: { status: "D" } }, multi: true },
  6. { q: { _id: 5 }, u: { _id: 5, name: "abc123", status: "A" }, upsert: true }
  7. ],
  8. ordered: false,
  9. writeConcern: { w: "majority", wtimeout: 5000 }
  10. }
  11. )

The returned document shows that the command modified 10 documentsand inserted a document with the _id value 5. SeeOutput for details.

  1. {
  2. "ok" : 1,
  3. "nModified" : 10,
  4. "n" : 11,
  5. "upserted" : [
  6. {
  7. "index" : 1,
  8. "_id" : 5
  9. }
  10. ]
  11. }

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:

  1. { _id: 1, category: "café", status: "A" }
  2. { _id: 2, category: "cafe", status: "a" }
  3. { _id: 3, category: "cafE", status: "a" }

The following operation includes the collationoption:

  1. db.runCommand({
  2. update: "myColl",
  3. updates: [
  4. { q: { category: "cafe", status: "a" }, u: { $set: { status: "Updated" } }, collation: { locale: "fr", strength: 1 } }
  5. ]
  6. })

Specify arrayFilters for 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 followingdocuments:

  1. db.students.insert([
  2. { "_id" : 1, "grades" : [ 95, 92, 90 ] },
  3. { "_id" : 2, "grades" : [ 98, 100, 102 ] },
  4. { "_id" : 3, "grades" : [ 95, 110, 100 ] }
  5. ]);

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:

  1. db.runCommand({
  2. update: "students",
  3. updates: [
  4. { q: { grades: { $gte: 100 } }, u: { $set: { "grades.$[element]" : 100 } }, arrayFilters: [ { "element": { $gte: 100 } } ], multi: true}
  5. ]
  6. })

After the operation, the collection contains the following documents:

  1. { "_id" : 1, "grades" : [ 95, 92, 90 ] }
  2. { "_id" : 2, "grades" : [ 98, 100, 100 ] }
  3. { "_id" : 3, "grades" : [ 95, 100, 100 ] }

Update Specific Elements of an Array of Documents

Create a collection students2 with the following documents:

  1. db.students2.insert([
  2. {
  3. "_id" : 1,
  4. "grades" : [
  5. { "grade" : 80, "mean" : 75, "std" : 6 },
  6. { "grade" : 85, "mean" : 90, "std" : 4 },
  7. { "grade" : 85, "mean" : 85, "std" : 6 }
  8. ]
  9. },
  10. {
  11. "_id" : 2,
  12. "grades" : [
  13. { "grade" : 90, "mean" : 75, "std" : 6 },
  14. { "grade" : 87, "mean" : 90, "std" : 3 },
  15. { "grade" : 85, "mean" : 85, "std" : 4 }
  16. ]
  17. }
  18. ]);

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:

  1. db.runCommand({
  2. update: "students2",
  3. updates: [
  4. { q: { }, u: { $set: { "grades.$[elem].mean" : 100 } }, arrayFilters: [ { "elem.grade": { $gte: 85 } } ], multi: true }
  5. ]
  6. })

After the operation, the collection has the following documents:

  1. {
  2. "_id" : 1,
  3. "grades" : [
  4. { "grade" : 80, "mean" : 75, "std" : 6 },
  5. { "grade" : 85, "mean" : 100, "std" : 4 },
  6. { "grade" : 85, "mean" : 100, "std" : 6 }
  7. ]
  8. }
  9. {
  10. "_id" : 2,
  11. "grades" : [
  12. { "grade" : 90, "mean" : 100, "std" : 6 },
  13. { "grade" : 87, "mean" : 100, "std" : 3 },
  14. { "grade" : 85, "mean" : 100, "std" : 4 }
  15. ]
  16. }

Specify hint for Update Operations

New in version 4.2.

Create a sample members collection with the following documents:

  1. db.members.insertMany([
  2. { "_id" : 1, "member" : "abc123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
  3. { "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" },
  4. { "_id" : 3, "member" : "lmn123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
  5. { "_id" : 4, "member" : "pqr123", "status" : "D", "points" : 20, "misc1" : "Deactivated", "misc2" : null },
  6. { "_id" : 5, "member" : "ijk123", "status" : "P", "points" : 0, "misc1" : null, "misc2" : null },
  7. { "_id" : 6, "member" : "cde123", "status" : "A", "points" : 86, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment" }
  8. ])

Create the following indexes on the collection:

  1. db.members.createIndex( { status: 1 } )
  2. 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.

  1. db.runCommand({
  2. update: "members",
  3. updates: [
  4. { q: { "points": { $lte: 20 }, "status": "P" }, u: { $set: { "misc1": "Need to activate" } }, hint: { status: 1 }, multi: true }
  5. ]
  6. })

The update command returns the following:

  1. { "n" : 3, "nModified" : 3, "ok" : 1 }

To see the index used, run explain on the operation:

  1. db.runCommand(
  2. {
  3. explain: {
  4. update: "members",
  5. updates: [
  6. { q: { "points": { $lte: 20 }, "status": "P" }, u: { $set: { "misc1": "Need to activate" } }, hint: { status: 1 }, multi: true }
  7. ]
  8. },
  9. verbosity: "queryPlanner"
  10. }
  11. )

The explain does not modify the documents.

Output

The returned document contains a subset of the following fields:

  • update.ok
  • The status of the command.
  • update.n
  • The number of documents selected for update. If the update operationresults in no change to the document, e.g. $set expressionupdates the value to the current value, n can begreater than nModified.
  • update.nModified
  • The number of documents updated. If the update operation results inno change to the document, such as setting the value of the field toits current value, nModified can be less thann.
  • update.upserted
  • An array of documents that contains information for each documentinserted through the update with upsert: true.

Each document contains the following information:

  • update.upserted.index
  • An integer that identifies the update with upsert:truestatement in the updates array, which uses a zero-based index.

  • update.upserted._id

  • The _id value of the added document.
  • update.writeErrors
  • An array of documents that contains information regarding any errorencountered during the update operation. ThewriteErrors array contains an error document foreach update statement that errors.

Each error document contains the following fields:

  • update.writeErrors.index
  • An integer that identifies the update statement in theupdates array, which uses a zero-based index.

  • update.writeErrors.code

  • An integer value identifying the error.

  • update.writeErrors.errmsg

  • A description of the error.
  • update.writeConcernError
  • Document that describe error related to write concern and containsthe field:

    • update.writeConcernError.code
    • An integer value identifying the cause of the write concern error.

    • update.writeConcernError.errmsg

    • A description of the cause of the write concern error.

In addition to the aforementioned update specific return fields, thedb.runCommand() includes additional information:

  • for replica sets: optime, electionId, $clusterTime, andoperationTime.
  • for sharded clusters: operationTime and $clusterTime.

See db.runCommand Response for details onthese fields.

The following is an example document returned for a successfulupdate command that performed an upsert:

  1. {
  2. "ok" : 1,
  3. "nModified" : 0,
  4. "n" : 1,
  5. "upserted" : [
  6. {
  7. "index" : 0,
  8. "_id" : ObjectId("52ccb2118908ccd753d65882")
  9. }
  10. ]
  11. }

The following is an example document returned for a bulk updateinvolving three update statements, where one update statement wassuccessful and two other update statements encountered errors:

  1. {
  2. "ok" : 1,
  3. "nModified" : 1,
  4. "n" : 1,
  5. "writeErrors" : [
  6. {
  7. "index" : 1,
  8. "code" : 16837,
  9. "errmsg" : "The _id field cannot be changed from {_id: 1.0} to {_id: 5.0}."
  10. },
  11. {
  12. "index" : 2,
  13. "code" : 16837,
  14. "errmsg" : "The _id field cannot be changed from {_id: 2.0} to {_id: 6.0}."
  15. },
  16. ]
  17. }