update-many
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset
Available tabs: other tabs: sync, async -->
Update Many
Overview
In this guide, you can learn how to use the MongoDB .NET/C# Driver to update values in multiple documents.
The .NET/C# Driver provides the following methods to update values:
-
UpdateMany(): Updates one or more fields in multiple documents. -
UpdateManyAsync(): The asynchronous version ofUpdateMany().
The following sections describe these methods in more detail.
Note: Method Overloads
Many of the methods on this page have multiple overloads. The examples in this guide show only one definition of each method. For more information about the available overloads, see the API documentation.
Important: Input Validation
Builder classes and LINQ queries pass values to the underlying MongoDB operation. By design, these APIs are not a security sanitization layer. Validate and sanitize untrusted input in your application before you pass it to a builder or a LINQ query.
Sample Data
The examples in this guide use the restaurants collection from the sample_restaurants database. The documents in this collection use the following Restaurant, Address, and GradeEntry classes as models:
public class Restaurant
{
public ObjectId Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
public string RestaurantId { get; set; }
public string Cuisine { get; set; }
public Address Address { get; set; }
public string Borough { get; set; }
public List<GradeEntry> Grades { get; set; }
}
public class Address
{
public string Building { get; set; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
public string ZipCode { get; set; }
}
public class GradeEntry
{
public DateTime Date { get; set; }
public string Grade { get; set; }
public float? Score { get; set; }
}
Note:
The documents in the restaurants collection use the snake-case naming convention. The examples in this guide use a ConventionPack to deserialize the fields in the collection into Pascal case and map them to the properties in the Restaurant class.
To learn more about custom serialization, see [Custom Serialization.](https://www.mongodb.com/docs/drivers/csharp/current/serialization/poco.md#std-label-csharp-custom-serialization
This collection is from the sample datasets provided by Atlas. See the [Get Started with the .NET/C# Driver](https://www.mongodb.com/docs/drivers/csharp/current/get-started.md#std-label-csharp-get-started to learn how to create a free MongoDB cluster and load this sample data.
Methods and Parameters
The UpdateMany() and UpdateManyAsync() methods accept the following parameters:
| Parameter | Description |
|---|---|
filter |
An instance of the FilterDefinition class that specifies the documents to update. To learn how to create a query filter, see [Create a Query Filter.](https://www.mongodb.com/docs/drivers/csharp/current/crud/query/query-filter.md#std-label-csharp-specify-query Data Type: FilterDefinition |
update |
An instance of the UpdateDefinition class. This object specifies the kind of update operation, the fields to update, and the new value for each field. To learn how to create an UpdateDefinition object, see [Update Fields in Many Documents](https://www.mongodb.com/docs/drivers/csharp/current/crud/update-many/fields.md#std-label-csharp-update-many-fields and [Update Arrays in Many Documents](https://www.mongodb.com/docs/drivers/csharp/current/crud/update-many/arrays.md#std-label-csharp-update-many-arrays. Data Type: UpdateDefinition<TDocument> |
options |
Optional. An instance of the UpdateOptions class that specifies the configuration for the update operation. The default value is null. For a list of available options, see [Configuration Options](https://www.mongodb.com/docs/drivers/csharp/current/crud/update-many.md#std-label-csharp-update-many-options-1. Data Type: UpdateOptions |
cancellationToken |
Optional. A token that you can use to cancel the operation. Data type: CancellationToken |
Update Multiple Values
The UpdateMany() and UpdateManyAsync() methods each accept only one UpdateDefinition object. The following sections describe how to update multiple values in a single method call.
Combined Update Definitions
The Builders.Update.Combine() method lets you combine multiple UpdateDefinition objects. This method accepts the following parameter:
| Parameter | Description |
|---|---|
updates |
An array of update definitions to combine. Data Type: UpdateDefinition<TDocument>[] |
The Combine() method returns a single UpdateDefinition object that defines multiple update operations.
The following code example uses the Combine() method to combine a [$set](https://www.mongodb.com/docs/manual/reference/operator/update/set/#mongodb-update-up.-set operation and an [$unset](https://www.mongodb.com/docs/manual/reference/operator/update/unset/#mongodb-update-up.-unset operation:
UpdateMany (Sync)
var filter = Builders<Restaurant>.Filter
.Eq("cuisine", "Pizza");
var combinedUpdate = Builders<Restaurant>.Update.Combine(
Builders<Restaurant>.Update.Set("cuisine", "French"),
Builders<Restaurant>.Update.Unset("borough")
);
_restaurantsCollection.UpdateMany(filter, combinedUpdate);
Update Pipelines
You can join a sequence of update operations into a single aggregation pipeline.
To create an update pipeline, call the Builders.Update.Pipeline() method. This method accepts the following parameter:
| Parameter | Description |
|---|---|
pipeline |
A PipelineDefinition instance that represents the update pipeline. To create a PipelineDefinition object, create a BSON document for each update operation you want to perform, then pass these documents to the PipelineDefinition.Create() method. Data Type: PipelineDefinition<TDocument, TDocument> |
The Pipeline() method returns a single UpdateDefinition object that defines multiple aggregation stages.
The following code example uses the Pipeline() method to combine a [$set](https://www.mongodb.com/docs/manual/reference/operator/update/set/#mongodb-update-up.-set operation and an [$unset](https://www.mongodb.com/docs/manual/reference/operator/update/unset/#mongodb-update-up.-unset operation:
UpdateMany (Sync)
var filter = Builders<Restaurant>.Filter
.Eq("cuisine", "Pizza");
var updatePipeline = Builders<Restaurant>.Update.Pipeline(
PipelineDefinition<Restaurant, Restaurant>.Create(
new BsonDocument("$set", new BsonDocument("cuisine", "French")),
new BsonDocument("$unset", "borough")
)
);
_restaurantsCollection.UpdateMany(filter, updatePipeline);
Note: Unsupported Operations
Update pipelines don't support all update operations, but they do support certain aggregation stages not found in other update definitions. For a list of update operations supported by pipelines, see Updates with Aggregation Pipeline in the MongoDB Server manual.
Configuration Options
The UpdateMany() and UpdateManyAsync() methods optionally accept an UpdateOptions object as a parameter. You can use this argument to configure the update operation.
The UpdateOptions class contains the following properties:
| Property | Description |
|---|---|
ArrayFilters |
Specifies which array elements to modify for an update operation on an array field. See [the MongoDB Server manual](https://www.mongodb.com/docs/manual/reference/command/update/#update-elements-match-arrayfilters-criteria for more information. Data Type: IEnumerable<ArrayFilterDefinition> |
BypassDocumentValidation |
Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. See [the MongoDB Server manual](https://www.mongodb.com/docs/manual/core/schema-validation/#schema-validation for more information on schema validation. Data Type: bool? |
Collation |
Specifies the kind of language collation to use when sorting results. See the [Collation](https://www.mongodb.com/docs/drivers/csharp/current/crud/query/find.md#std-label-csharp-find-collation section of this page for more information. Data Type: Collation |
Comment |
Gets or sets the user-provided comment for the operation. See [the MongoDB Server manual](https://www.mongodb.com/docs/manual/reference/command/update/#command-fields for more information. Data Type: BsonValue |
Hint |
Gets or sets the index to use to scan for documents. See [the MongoDB Server manual](https://www.mongodb.com/docs/manual/reference/command/update/#std-label-update-command-hint for more information. Data Type: BsonValue |
IsUpsert |
Specifies whether the update operation performs an upsert operation if no documents match the query filter. See [the MongoDB Server manual](https://www.mongodb.com/docs/manual/reference/command/update/#std-label-update-command-upsert for more information. Data Type: bool |
Sort |
Determines which document the operation updates if the query selects multiple documents, because the update operation updates the first document in the sort order specified. To set this option, you must instantiate an UpdateOptions<T> instance that uses a generic type that models your data, as shown in the following code: `var options = new UpdateOptions<Restaurant> |
| { | |
| Sort = Builders<Restaurant>.Sort.Ascending(r => r.Name) | |
};**Data Type:**SortDefinition<T>` |
|
Let |
Gets or sets the let document. See [the MongoDB Server manual](https://www.mongodb.com/docs/manual/reference/command/update/#std-label-update-let-syntax for more information. Data Type: BsonDocument |
Collation
To configure collation for your operation, create an instance of the Collation class.
The following table describes the parameters that the Collation constructor accepts. It also lists the corresponding class property that you can use to read each setting's value.
| Parameter | Description | Class Property |
|---|---|---|
locale |
Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see [Collation Locales and Default Parameters](https://www.mongodb.com/docs/manual/reference/collation-locales-defaults/#supported-languages-and-locales in the MongoDB Server Manual.If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to “simple”.Data Type: string |
Locale |
caseLevel |
(Optional) Specifies whether to include case comparison.When this argument is true, the driver's behavior depends on the value of the strength argument:- If strength is CollationStrength.Primary, the driver compares base characters and case.- If strength is CollationStrength.Secondary, the driver compares base characters, diacritics, other secondary differences, and case.- If strength is any other value, this argument is ignored.When this argument is false, the driver doesn't include case comparison at strength level Primary or Secondary.Data Type: booleanDefault: false |
CaseLevel |
caseFirst |
(Optional) Specifies the sort order of case differences during tertiary level comparisons.Data Type: CollationCaseFirstDefault: CollationCaseFirst.Off |
CaseFirst |
strength |
(Optional) Specifies the level of comparison to perform, as defined in the [ICU documentation](https://unicode-org.github.io/icu/userguide/collation/concepts.html#comparison-levels.Data Type: CollationStrengthDefault: CollationStrength.Tertiary |
Strength |
numericOrdering |
(Optional) Specifies whether the driver compares numeric strings as numbers.If this argument is true, the driver compares numeric strings as numbers. For example, when comparing the strings “10” and “2”, the driver treats the values as 10 and 2, and finds 10 to be greater.If this argument is false or excluded, the driver compares numeric strings as strings. For example, when comparing the strings “10” and “2”, the driver compares one character at a time. Because “1” is less than “2”, the driver finds “10” to be less than “2”.For more information, see [Collation Restrictions](https://www.mongodb.com/docs/manual/reference/collation/#restrictions in the MongoDB Server manual.Data Type: booleanDefault: false |
NumericOrdering |
alternate |
(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.Data Type: CollationAlternateDefault: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters) |
Alternate |
maxVariable |
(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.Data Type: CollationMaxVariableDefault: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces) |
MaxVariable |
normalization |
(Optional) Specifies whether the driver normalizes text as needed.Most text doesn't require normalization. For more information about normalization, see the [ICU documentation](https://unicode-org.github.io/icu/userguide/collation/concepts.html#normalization.Data Type: booleanDefault: false |
Normalization |
backwards |
(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.Data Type: booleanDefault: false |
Backwards |
For more information about collation, see the Collation page in the MongoDB Server manual.
Return Value
The UpdateMany() method returns an UpdateResult, and the UpdateManyAsync() method returns a Task<UpdateResult> object. The UpdateResult class contains the following properties:
| Property | Description |
|---|---|
IsAcknowledged |
Indicates whether the update operation was acknowledged by MongoDB. Data Type: bool |
IsModifiedCountAvailable |
Indicates whether you can read the count of update records on the UpdateResult. Data Type: bool |
MatchedCount |
The number of documents that matched the query filter, regardless of whether one was updated. Data Type: long |
ModifiedCount |
The number of documents updated by the update operation. Data Type: long |
UpsertedId |
The ID of the document that was upserted in the database, if the driver performed an upsert. Data Type: BsonValue |
Additional Information
This page includes a short interactive lab that demonstrates how to modify data by using the UpdateManyAsync() method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.
To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.
For runnable examples of the update operations, see the following usage examples:
To learn more about creating query filters, see the [Create a Query Filter](https://www.mongodb.com/docs/drivers/csharp/current/crud/query/query-filter.md#std-label-csharp-specify-query guide.
API Documentation
For more information about any of the methods or types discussed in this guide, see the following API documentation:
