Mongodb compass update multiple documents

Docs HomeMongoDB Compass

You can edit existing documents in your collection.

When you edit a document in List or Table view, Compass performs a findOneAndUpdate operation and updates only those fields that you have changed.

When you edit a document in JSON view, Compass performs a findOneAndReplace operation and replaces the document.

  • Modifying documents is not permitted in MongoDB Compass Readonly Edition.

Select the appropriate tab based on whether you are viewing your documents in List, JSON, or Table view:

Mongodb compass update multiple documents

To exit the edit mode and cancel all pending changes to the document, click the Cancel button.

Docs HomeMongoDB Manual


➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.


Note

Starting in MongoDB 4.2, MongoDB can accept an aggregation pipeline to specify the modifications to make instead of an update document. See the method reference page for details.

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.

Once set, you cannot update the value of the _id field nor can you replace an existing document with a replacement document that has a different _id field value.

For write operations, MongoDB preserves the order of the document fields except for the following cases:

  • The _id field is always the first field in the document.

  • Updates that include renaming of field names may result in the reordering of fields in the document.

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

Docs HomeMongoDB Manual

db.collection.updateMany(filter, update, options)

Important

mongosh Method

This page documents a mongosh method. This is not the documentation for a language-specific driver, such as Node.js.

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.

Updates all documents that match the specified filter for a collection.

The updateMany() method has the following form:

db.collection.updateMany(
,
,
{
upsert: ,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ , ... ],
hint: // Available starting in MongoDB 4.2.1
}
)

The updateMany() method takes the following parameters:

Parameter

Type

Description

filter

document

The selection criteria for the update. The same query selectors as in the find() method are available.

Specify an empty document { } to update all documents in the collection.

update

document or pipeline

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

Update document

Contains only update operator expressions.

For more information, see Update with an Update Operator Expressions Document

Aggregation pipeline (Starting in MongoDB 4.2)

Contains only the following aggregation stages:

  • $addFields and its alias $set

  • $project and its alias $unset

  • $replaceRoot and its alias $replaceWith.

For more information, see Update with an Aggregation Pipeline.

To update with a replacement document, see db.collection.replaceOne().

upsert

boolean

Optional. When true, updateMany() either:

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

  • Updates documents that match the filter.

To avoid multiple upserts, ensure that the filter fields are 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 in a transaction. To use write concern with transactions, see Transactions and Write Concern.

collation

document

Optional.

Specifies the collation to use for the operation.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

The collation option has the following syntax:

collation: {
locale: ,
caseLevel: ,
caseFirst: ,
strength: ,
numericOrdering: ,
alternate: ,
maxVariable: ,
backwards:
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.

arrayFilters

array

Optional. An array of filter documents that determine which array elements to modify for an update operation on an array field.

In the update document, use the $[] filtered positional operator to define an identifier, which you then reference in the array filter documents. You cannot have an array filter document for an identifier if the identifier is not included in the update document.

Note

The must begin with a lowercase letter and contain only alphanumeric characters.

You can include the same identifier multiple times in the update document; however, for each distinct identifier ($[identifier]) in the update document, you must specify exactly one corresponding array filter document. That is, you cannot specify multiple array filter documents for the same identifier. For example, if the update statement includes the identifier x (possibly multiple times), you cannot specify the following for arrayFilters 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 identifier in 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 } }
]

For examples, see Specify arrayFilters for an Array Update Operations.

hint

Document or string

Optional. A document or string that specifies the index to use to support the query predicate.

The option can take an index specification document or the index name string.

If you specify an index that does not exist, the operation errors.

For an example, see Specify hint for Update Operations.

New in version 4.2.1.

The method returns a document that contains:

  • A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled

  • matchedCount containing the number of matched documents

  • modifiedCount containing the number of modified documents

  • upsertedId containing the _id for the upserted document

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.

updateMany() updates all matching documents in the collection that match the filter, using the update criteria to apply modifications.

If upsert: true and no documents match the filter, db.collection.updateMany() creates a new document based on the filter and update parameters.

If you specify upsert: true on a sharded collection, you must include the full shard key in the filter. For additional db.collection.updateMany() behavior, see Sharded Collections.

See Update Multiple Documents with Upsert.

For the modification specification, the db.collection.updateMany() method can accept a document that only contains update operator expressions to perform.

For example:

db.collection.updateMany(
,
{ $set: { status: "D" }, $inc: { quantity: 2 } },
...
)

Starting in MongoDB 4.2, the db.collection.updateMany() method can accept an aggregation pipeline [ , , ... ] that specifies the modifications to perform. The pipeline can consist of the following stages:

  • $addFields and its alias $set

  • $project and its alias $unset

  • $replaceRoot and its alias $replaceWith.

Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).

For example:

db.collection.updateMany(
,
[
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ] } },
{ $unset: [ "misc1", "misc2" ] }
]
...
)

Note

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

For examples, see Update with Aggregation Pipeline.

If an update operation changes the document size, the operation will fail.

You cannot use the updateMany() method on a time series collection.

For a db.collection.updateMany() operation that includes upsert: true and is on a sharded collection, you must include the full shard key in the filter.

updateMany() is not compatible with db.collection.explain().

db.collection.updateMany() can be used inside multi-document transactions.

Important

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.

Starting in MongoDB 4.4, you can create collections and indexes inside a multi-document transaction if the transaction is not a cross-shard write transaction.

Specifically, in MongoDB 4.4 and greater, db.collection.updateMany() 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.

In MongoDB 4.2 and earlier, the operation must be run on an existing collection.

Tip

See also:

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.

The restaurant collection contains the following documents:

{ "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
{ "_id" : 3, "name" : "Empire State Sub", "violations" : 5 }
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8 }

The following operation updates all documents where violations are greater than 4 and $set a flag for review:

try {
db.restaurant.updateMany(
{ violations: { $gt: 4 } },
{ $set: { "Review" : true } }
);
} catch (e) {
print(e);
}

The operation returns:

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

The collection now contains the following documents:

{ "_id" : 1, "name" : "Central Perk Cafe", "violations" : 3 }
{ "_id" : 2, "name" : "Rock A Feller Bar and Grill", "violations" : 2 }
{ "_id" : 3, "name" : "Empire State Sub", "violations" : 5, "Review" : true }
{ "_id" : 4, "name" : "Pizza Rat's Pizzaria", "violations" : 8, "Review" : true }

If no matches were found, the operation instead returns:

{ "acknowledged" : true, "matchedCount" : 0, "modifiedCount" : 0 }

Setting upsert: true would insert a document if no match was found.

Starting in MongoDB 4.2, the db.collection.updateMany() can use an aggregation pipeline for the update. The pipeline can consist of the following stages:

  • $addFields and its alias $set

  • $project and its alias $unset

  • $replaceRoot and its alias $replaceWith.

Using the aggregation pipeline allows for a more expressive update statement, such as expressing conditional updates based on current field values or updating one field using the value of another field(s).

The following examples uses the aggregation pipeline to modify a field using the values of the other fields in the document.

Create a members collection with the following documents:

db.members.insertMany( [
{ "_id" : 1, "member" : "abc123", "status" : "A", "points" : 2, "misc1" : "note to self: confirm status", "misc2" : "Need to activate", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "member" : "xyz123", "status" : "A", "points" : 60, "misc1" : "reminder: ping me at 100pts", "misc2" : "Some random comment", "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
] )

Assume that instead of separate misc1 and misc2 fields, you want to gather these into a new comments field. The following update operation uses an aggregation pipeline to:

  • add the new comments field and set the lastUpdate field.

  • remove the misc1 and misc2 fields for all documents in the collection.

db.members.updateMany(
{ },
[
{ $set: { status: "Modified", comments: [ "$misc1", "$misc2" ], lastUpdate: "$$NOW" } },
{ $unset: [ "misc1", "misc2" ] }
]
)

Note

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

First Stage

The $set stage:

  • creates a new array field comments whose elements are the current content of the misc1 and misc2 fields and

  • sets the field lastUpdate to the value of the aggregation variable NOW. The aggregation variable NOW resolves to the current datetime value and remains the same throughout the pipeline. To access aggregation variables, prefix the variable with double dollar signs $$ and enclose in quotes.

Second StageThe $unset stage removes the misc1 and misc2 fields.

After the command, the collection contains the following documents:

{ "_id" : 1, "member" : "abc123", "status" : "Modified", "points" : 2, "lastUpdate" : ISODate("2020-01-23T05:50:49.247Z"), "comments" : [ "note to self: confirm status", "Need to activate" ] }
{ "_id" : 2, "member" : "xyz123", "status" : "Modified", "points" : 60, "lastUpdate" : ISODate("2020-01-23T05:50:49.247Z"), "comments" : [ "reminder: ping me at 100pts", "Some random comment" ] }

The aggregation pipeline allows the update to perform conditional updates based on the current field values as well as use current field values to calculate a separate field value.

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

db.students3.insertMany( [
{ "_id" : 1, "tests" : [ 95, 92, 90 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") },
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2019-01-01T00:00:00Z") }
] )

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

db.students3.updateMany(
{ },
[
{ $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] } , lastUpdate: "$$NOW" } },
{ $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 field average based on the average of the tests field. See $avg for more information on the $avg aggregation operator and $trunc for more information on the $trunc truncate aggregation operator.

  • sets the field lastUpdate to the value of the aggregation variable NOW. The aggregation variable NOW resolves to the current datetime value and remains the same throughout the pipeline. To access aggregation variables, prefix the variable with double dollar signs $$ and enclose in quotes.

Second StageThe $set stage calculates a new field grade based on the average 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 ], "lastUpdate" : ISODate("2020-01-24T17:31:01.670Z"), "average" : 92, "grade" : "A" }
{ "_id" : 2, "tests" : [ 94, 88, 90 ], "lastUpdate" : ISODate("2020-01-24T17:31:01.670Z"), "average" : 90, "grade" : "A" }
{ "_id" : 3, "tests" : [ 70, 75, 82 ], "lastUpdate" : ISODate("2020-01-24T17:31:01.670Z"), "average" : 75, "grade" : "C" }

Tip

See also:

The inspectors collection contains the following documents:

{ "_id" : 92412, "inspector" : "F. Drebin", "Sector" : 1, "Patrolling" : true },
{ "_id" : 92413, "inspector" : "J. Clouseau", "Sector" : 2, "Patrolling" : false },
{ "_id" : 92414, "inspector" : "J. Clouseau", "Sector" : 3, "Patrolling" : true },
{ "_id" : 92415, "inspector" : "R. Coltrane", "Sector" : 3, "Patrolling" : false }

The following operation updates all documents with Sector greater than 4 and inspector equal to "R. Coltrane":

try {
db.inspectors.updateMany(
{ "Sector" : { $gt : 4 }, "inspector" : "R. Coltrane" },
{ $set: { "Patrolling" : false } },
{ upsert: true }
);
} catch (e) {
print(e);
}

The operation returns:

{
"acknowledged" : true,
"matchedCount" : 0,
"modifiedCount" : 0,
"upsertedId" : ObjectId("56fc5dcb39ee682bdc609b02")
}

The collection now contains the following documents:

{ "_id" : 92412, "inspector" : "F. Drebin", "Sector" : 1, "Patrolling" : true },
{ "_id" : 92413, "inspector" : "J. Clouseau", "Sector" : 2, "Patrolling" : false },
{ "_id" : 92414, "inspector" : "J. Clouseau", "Sector" : 3, "Patrolling" : true },
{ "_id" : 92415, "inspector" : "R. Coltrane", "Sector" : 3, "Patrolling" : false },
{ "_id" : ObjectId("56fc5dcb39ee682bdc609b02"), "inspector" : "R. Coltrane", "Patrolling" : false }

Since no documents matched the filter, and upsert was true, updateMany() inserted the document with a generated _id, the equality conditions from the filter, and the update modifiers.

Given a three member replica set, the following operation specifies a w of majority and wtimeout of 100:

try {
db.restaurant.updateMany(
{ "name" : "Pizza Rat's Pizzaria" },
{ $inc: { "violations" : 3}, $set: { "Closed" : true } },
{ w: "majority", wtimeout: 100 }
);
} catch (e) {
print(e);
}

If the acknowledgement takes longer than the wtimeout limit, the following exception is thrown:

Changed in version 4.4.

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 errInfo.writeConcern.provenance:

Provenance

Description

clientSupplied

The write concern was specified in the application.

customDefault

The write concern originated from a custom defined default value. See setDefaultRWConcern.

getLastErrorDefaults

The write concern originated from the replica set's settings.getLastErrorDefaults field.

implicitDefault

The write concern originated from the server in absence of all other write concern specifications.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

A collection myColl has the following documents:

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

The following operation includes the collation option:

db.myColl.updateMany(
{ category: "cafe" },
{ $set: { status: "Updated" } },
{ collation: { locale: "fr", strength: 1 } }
);

Starting in MongoDB 3.6, when updating an array field, you can specify arrayFilters that determine which array elements to update.

Create a collection students 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 the grades array, use the filtered positional operator $[] with the arrayFilters option:

db.students.updateMany(
{ grades: { $gte: 100 } },
{ $set: { "grades.$[element]" : 100 } },
{ 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 ] }

Create a collection students2 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 the grades array where the grade is greater than or equal to 85, use the filtered positional operator $[] with the arrayFilters:

db.students2.updateMany(
{ },
{ $set: { "grades.$[elem].mean" : 100 } },
{ 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 }
]
}

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.updateMany(
{ "points": { $lte: 20 }, "status": "P" },
{ $set: { "misc1": "Need to activate" } },
{ hint: { status: 1 } }
)

The update command returns the following:

{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

To view the indexes used, you can use the $indexStats pipeline:

db.members.aggregate( [ { $indexStats: { } }, { $sort: { name: 1 } } ] )

How do I update my compass?

If you are set to receive updates manually, log in to Compass as an Org Administrator or Org Member, select “Updates” from the menu on the left and follow the onscreen prompts.

How do I update multiple columns in MongoDB?

Update Multiple Fields of a Single Document. We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.

Where is find and replace in MongoDB compass?

In MongoDB, you are allowed to replace an existing document with a new document in the collection with the help of db. collection. replaceOne() method. This method will replace the existing document with the replacement document.

How do you update an array of objects in MongoDB?

Update Values in an Array. Create a collection students with the following documents: ... .
Update Documents in an Array. The positional $ operator facilitates updates to arrays that contain embedded documents. ... .
Update Embedded Documents Using Multiple Field Matches. ... .
Update with Multiple Array Matches..