Replace Documents
Overview
In this guide, you can learn how to use the .NET/C# Driver to replace documents in a MongoDB collection.
The .NET/C# Driver provides the ReplaceOne()
and ReplaceOneAsync()
methods.
These methods remove all fields (except the _id
field) from the first document that
matches the search criteria, then insert the fields and values you specify into the
document.
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.
Replace One Document
To replace a document in a collection, call the ReplaceOne()
or ReplaceOneAsync()
method. These methods accept the following parameters:
Parameter | Description |
---|---|
| A query filter that specifies the document to replace. You can use the
Data Type: FilterDefinition<TDocument> |
| A replacement document, which specifies the fields and values to insert in the new document. If the documents in your collection are mapped to a C# class, the replacement document can be an instance of this class. Data Type: |
| Optional. An instance of the Data Type: ReplaceOptions |
| Optional. A token that you can use to cancel the operation. Data type: CancellationToken |
The following code example demonstrates how to perform a replace operation. The code performs the following steps:
Creates a query filter by using the
Builders
class. The filter matches all documents where thecuisine
field has the value"Pizza"
.Creates a new
Restaurant
object.Calls the
ReplaceOne()
method on therestaurants
collection. This operation finds the first matching document in the collection and replaces it with the newly created document.
Select the Synchronous or Asynchronous tab to see the corresponding code.
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Asynchronously replaces the existing restaurant document with the new document return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);
Important
The values of _id
fields are immutable. If your replacement document specifies
a value for the _id
field, it must match the _id
value of the existing document.
Customize the Replace Operation
The ReplaceOne()
and ReplaceOneAsync()
methods optionally accept a
ReplaceOptions
object as a parameter, which represents options you can use to
configure the replace operation.
The ReplaceOptions
class contains the following properties:
Property | Description |
---|---|
| Specifies whether the replace operation bypasses document validation. This lets you replace 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 replace 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 |
The following example performs the same steps as the preceding example, but also uses
the BypassDocumentValidation
option to bypass any schema validation requirements.
Select the Synchronous or Asynchronous tab to see the corresponding
code.
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; var options = new ReplaceOptions { BypassDocumentValidation = true }; // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant, options);
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; var options = new ReplaceOptions { BypassDocumentValidation = true }; // Asynchronously replaces the existing restaurant document with the new document return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant, options);
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 ReplaceOne()
method returns a ReplaceOneResult
object, and the ReplaceOneAsync()
method returns a Task<ReplaceOneResult>
object.
The ReplaceOneResult
class contains the following properties:
Property | Description |
---|---|
| Indicates whether the replace operation was acknowledged by MongoDB. Data Type: |
| Indicates whether you can read the count of replaced records on the
Data Type: |
| The number of documents that matched the query filter, regardless of whether one was replaced. Data Type: |
| The number of documents replaced by the replace 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 replace operation, see the following usage examples:
API Documentation
To learn more about any of the methods and classes used on this page, see the following API documentation: