Docs Menu
Docs Home
/ / /
C#/.NET
/ / /

Update One

On this page

  • Overview
  • Sample Data
  • Methods and Parameters
  • Update Multiple Values
  • Combined Update Definitions
  • Update Pipelines
  • Configuration Options
  • Return Value
  • Additional Information
  • API Documentation

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 of UpdateOne().

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.

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 Quick Start to learn how to create a free MongoDB cluster and load this sample data.

The UpdateOne() and UpdateOneAsync() methods accept the following parameters:

Parameter
Description

filter

An instance of the FilterDefinition class that specifies the document to update. To learn how to create a query filter, see Specify a 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 and Update 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.

Data Type: UpdateOptions

cancellationToken

Optional. A token that you can use to cancel the operation.

Data type: CancellationToken

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.

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("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);

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

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("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.

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

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 MongoDB Server manual for more information on collation.

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

Let

Gets or sets the let document. See the MongoDB Server manual for more information.

Data Type: BsonDocument

The UpdateOne() method returns an UpdateResult, and the UpdateOneAsync() 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

For runnable examples of the update operations, see the Update a Document page.

To learn more about creating query filters, see the Specify a Query guide.

For more information about any of the methods or types discussed in this guide, see the following API documentation:

Back

Insert