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

Replace Documents

On this page

  • Overview
  • Sample Data
  • Replace One Document
  • Customize the Replace Operation
  • Return Value
  • API Documentation

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.

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.

To replace a document in a collection, call the ReplaceOne() or ReplaceOneAsync() method. These methods accept the following parameters:

Parameter
Description

filter

A query filter that specifies the document to replace. You can use the Builders class to create a query filter. For more information about query filters, see the MongoDB Server manual.

Data Type: FilterDefinition<TDocument>

replacement

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: TDocument

options

Optional. An instance of the ReplaceOptions class that specifies the configuration for the replace operation. The default value is null.

Data Type: ReplaceOptions

cancellationToken

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:

  1. Creates a query filter by using the Builders class. The filter matches all documents where the cuisine field has the value "Pizza".

  2. Creates a new Restaurant object.

  3. Calls the ReplaceOne() method on the restaurants 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.

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

BypassDocumentValidation

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: 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 replace 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 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);

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

IsAcknowledged

Indicates whether the replace operation was acknowledged by MongoDB.

Data Type: bool

IsModifiedCountAvailable

Indicates whether you can read the count of replaced records on the ReplaceOneResult.

Data Type: bool

MatchedCount

The number of documents that matched the query filter, regardless of whether one was replaced.

Data Type: long

ModifiedCount

The number of documents replaced by the replace 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

To learn more about any of the methods and classes used on this page, see the following API documentation:

Back

Arrays