Update One
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
If your application connects to MongoDB Server 4.2 or later, 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: |
| 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. 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 |
|
| (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 |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. Data Type: CollationCaseFirst Default: CollationCaseFirst.Off |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: CollationStrength Default: CollationStrength.Tertiary |
|
| (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
in the MongoDB Server manual. Data Type: boolean Default: false |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. Data Type: CollationAlternate Default: CollationAlternate.NonIgnorable (spaces and punctuation are
considered base characters) |
|
| (Optional) Specifies which characters the driver considers ignorable when
the alternate argument is CollationAlternate.Shifted .Data Type: CollationMaxVariable Default: CollationMaxVariable.Punctuation (the driver ignores punctuation
and spaces) |
|
| (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 |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolean Default: false |
|
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:
Sample Class
The code examples in this guide demonstrate how you can use builders to
create types to interact with documents in the sample collection plants.flowers
.
Documents in this collection are modeled by the following Flower
class:
public class Flower { public ObjectId Id { get; set; } public string Name { get; set; } public string Category { get; set; } public double Price { get; set; } public List<string> Season { get; set; } public double Stock { get; set; } public string Description { get; set; } }
Each builder class takes a generic type parameter
TDocument
which represents the type of document that you are working
with. In this guide, the Flower
class is the document type used in
each builder class example.
Define an Update
The UpdateDefinitionBuilder
class provides a type-safe interface for
building up an update specification. Suppose you want to create an
update specification with the following criteria:
Create the new field
SunRequirement
Multiply the
Price
field value by 0.9
Use builders to create the update specification with the typed variant:
var builder = Builders<Flower>.Update; var update = builder.Set(f => f.SunRequirement, "Full sun").Mul(f => f.Price, 0.9);
Alternatively, you can use string-based field names to define the update:
var builder = Builders<Flower>.Update; var update = builder.Set("SunRequirement", "Full sun").Mul("Price", 0.9);