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 of UpdateMany()
.
The following sections describe these methods in more detail.
Note Method OverloadsMany 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.
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.
This collection is from the sample datasets provided by Atlas. See the Get Started with the .NET/C# Driver to learn how to create a free MongoDB cluster and load this sample data.
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.
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 and Update Arrays in Many Documents.
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.
Data Type: UpdateOptions
cancellationToken
Optional. A token that you can use to cancel the operation.
Data type: CancellationToken
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.
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 operation and an $unset operation:
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);
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"));await _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate);
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 operation and an $unset operation:
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);
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") ));await _restaurantsCollection.UpdateManyAsync(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.
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 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 for more information on schema validation.
Data Type: bool?
Collation
Specifies the kind of language collation to use when sorting results. See the 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 for more information.
Data Type: BsonValue
Hint
Gets or sets the index to use to scan for documents. See the MongoDB Server manual 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 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 for more information.
Data Type: BsonDocument
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 Parametersin 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: boolean
Default: false
CaseLevel
caseFirst
(Optional) Specifies the sort order of case differences during tertiary level comparisons.
Data Type:
CollationCaseFirstDefault: CollationCaseFirst.Off
CaseFirst
strength
Specifies the level of comparison to perform, as defined in the
ICU documentation.
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 Restrictionsin the MongoDB Server manual.
Data Type: boolean
Default: 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
.
:
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.
Data Type: boolean
Default: false
Normalization
backwards
(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.
Data Type: boolean
Default: false
Backwards
For more information about collation, see the Collation page in the MongoDB Server manual.
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
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 guide.
For more information about any of the methods or types discussed in this guide, see the following API documentation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4