Overview
In this guide, you can learn how to use the MongoDB .NET/C# Driver to update values in a single document.
The .NET/C# Driver provides the following methods to update values:
UpdateOne(): Updates one or more fields in a single document.UpdateOneAsync(): The asynchronous version ofUpdateOne().
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.
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; } [] 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; } [] public double[] Coordinates { get; set; } public string Street { get; set; } [] 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.
Methods and Parameters
The UpdateOne() and UpdateOneAsync() methods accept the following parameters:
Parameter | Description |
|---|---|
| An instance of the Data Type: FilterDefinition |
| An instance of the Data Type: UpdateDefinition<TDocument> |
| Optional. An instance of the Data Type: UpdateOptions |
| Optional. A token that you can use to cancel the operation. Data type: |
Update Multiple Values
The UpdateOne() and UpdateOneAsync() 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 |
|---|---|
| An array of update definitions to combine. Data Type: |
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("name", "Downtown Deli"); var combinedUpdate = Builders<Restaurant>.Update.Combine( Builders<Restaurant>.Update.Set("cuisine", "French"), Builders<Restaurant>.Update.Unset("borough") ); _restaurantsCollection.UpdateOne(filter, combinedUpdate);
var filter = Builders<Restaurant>.Filter .Eq("name", "Downtown Deli"); var combinedUpdate = Builders<Restaurant>.Update.Combine( Builders<Restaurant>.Update.Set("cuisine", "French"), Builders<Restaurant>.Update.Unset("borough") ); await _restaurantsCollection.UpdateOneAsync(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 |
|---|---|
| A Data Type: |
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("name", "Downtown Deli"); var updatePipeline = Builders<Restaurant>.Update.Pipeline( PipelineDefinition<Restaurant, Restaurant>.Create( new BsonDocument("$set", new BsonDocument("cuisine", "French")), new BsonDocument("$unset", "borough") ) ); _restaurantsCollection.UpdateOne(filter, updatePipeline);
var filter = Builders<Restaurant>.Filter .Eq("name", "Downtown Deli"); var updatePipeline = Builders<Restaurant>.Update.Pipeline( PipelineDefinition<Restaurant, Restaurant>.Create( new BsonDocument("$set", new BsonDocument("cuisine", "French")), new BsonDocument("$unset", "borough") ) ); await _restaurantsCollection.UpdateOneAsync(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 UpdateOne() and UpdateOneAsync() 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 | ||||
|---|---|---|---|---|---|
| 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> | ||||
| 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: | ||||
| |||||
| Gets or sets the user-provided comment for the operation. See the MongoDB Server manual for more information. Data Type: BsonValue | ||||
| Gets or sets the index to use to scan for documents. See the MongoDB Server manual for more information. Data Type: BsonValue | ||||
| 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: | ||||
| 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 Data Type: | ||||
| Gets or sets the let document. See the MongoDB Server manual 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 |
|---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. |
|
| (Optional) Specifies whether to include case comparison. |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. |
|
| (Optional) Specifies which characters the driver considers ignorable when
the |
|
| (Optional) Specifies whether the driver normalizes text as needed. |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. |
|
For more information about collation, see the Collation page in the MongoDB Server manual.
Return Value
The UpdateOne() method returns an UpdateResult, and the UpdateOneAsync() method returns a Task<UpdateResult> object. The UpdateResult class contains the following properties:
Property | Description |
|---|---|
| Indicates whether the update operation was acknowledged by MongoDB. Data Type: |
| Indicates whether you can read the count of update records on the Data Type: |
| The number of documents that matched the query filter, regardless of whether one was updated. Data Type: |
| The number of documents updated by the update operation. Data Type: |
| The ID of the document that was upserted in the database, if the driver performed an upsert. Data Type: BsonValue |
Additional Information
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.
API Documentation
For more information about any of the methods or types discussed in this guide, see the following API documentation: