Replace Documents
On this page
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 Quick Start 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: |
| Specifies the kind of language collation to use when sorting results. See the MongoDB Server manual for more information on collation. Data Type: Collation |
| 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);
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 |
API Documentation
To learn more about any of the methods and classes used on this page, see the following API documentation: