Modify Documents
On this page
Overview
In this guide, you can learn how to use the MongoDB .NET/C# Driver to modify documents in a MongoDB collection by performing the following operations:
The .NET/C# Driver provides the following methods to modify documents, each of which has an asynchronous and synchronous version:
UpdateOneAsync()
orUpdateOne()
UpdateManyAsync()
orUpdateMany()
ReplaceOneAsync()
orReplaceOne()
Tip
Interactive Lab
This page includes a short interactive lab that demonstrates how to
modify data by using the UpdateManyAsync()
method. You can complete this
lab directly in your browser window without installing MongoDB or a code editor.
To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.
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.
Update Operations
You can perform update operations in MongoDB with the following methods:
UpdateOne()
, which updates the first document that matches the search criteriaUpdateMany()
, which updates all documents that match the search criteria
Required Parameters
Each update method requires the following parameters:
A query filter document, which determines which records to update. See the MongoDB server manual for more information about query filters.
An update document, which specifies the update operator (the kind of update to perform) and the fields and values that should change. See the Field Update Operators Manual page for a complete list of update operators and their usage.
The .NET/C# Driver provides a Builders
class that simplifies the creation of both
query filters and update documents. The following code sample uses Builders
to create
two documents for use as parameters in an update operation:
A query filter that searches for restaurants with a
cuisine
field value of "Pizza"An update document that sets the value of the
cuisine
field of these restaurants to "Pasta and breadsticks"
const string oldValue = "Pizza"; const string newValue = "Pasta and breadsticks"; // Creates a filter for all documents with a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Cuisine, oldValue); // Creates instructions to update the "cuisine" field of documents that // match the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Cuisine, newValue); // Updates all documents that have a "cuisine" value of "Pizza" return _restaurantsCollection.UpdateMany(filter, update);
Tip
Aggregation Pipelines in Update Operations
If you are using MongoDB Version 4.2 or later, you can use aggregation pipelines made up of a subset of aggregation stages in update operations. For more information on the aggregation stages MongoDB supports in aggregation pipelines used in update operations, see our tutorial on building updates with aggregation pipelines.
Update One Document
The following code shows how to use the asynchronous UpdateOneAsync()
method
or the synchronous UpdateOne()
method to update one document.
var result = await _restaurantsCollection.UpdateOneAsync(filter, update);
var result = _restaurantsCollection.UpdateOne(filter, update);
Update Many Documents
The following code shows how to use the asynchronous
UpdateManyAsync()
method or the synchronous UpdateMany()
method to
update all matched documents.
var result = await _restaurantsCollection.UpdateManyAsync(filter, update);
var result = _restaurantsCollection.UpdateMany(filter, update);
Tip
Find runnable examples that use these methods under Additional Information.
Customize the Update Operation
Both methods optionally accept an UpdateOptions
object as an additional parameter,
which represents options you can use to configure the update operation.
If you don't specify any UpdateOptions
properties, the driver does
not customize the update operation.
The UpdateOptions
type allows you to configure options with 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. |
| 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. |
| Specifies the kind of language collation to use when sorting
results. See the MongoDB server manual
for more information on collation. |
| Gets or sets the user-provided comment for the operation.
See the MongoDB server manual
for more information. |
| Gets or sets the index to use to scan for documents.
See the MongoDB server manual
for more information. |
| Specifies whether the update operation performs an upsert operation if no
documents match the query filter.
See the MongoDB server manual
for more information. |
| Gets or sets the let document.
See the MongoDB server manual
for more information. |
Return Value
The UpdateOne()
and UpdateMany()
methods each return an UpdateResult
object. The UpdateResult
type contains the following properties:
Property | Description |
---|---|
| Indicates whether the update operation was acknowledged by MongoDB. |
| Indicates whether you can read the count of updated records on the
UpdateResult . |
| The number of documents that matched the query filter, regardless of
how many were updated. |
| The number of documents updated by the update operation. If an updated
document is identical to the original, it won't be included in this count. |
| The ID of the document that was upserted in the database, if the driver
performed an upsert. |
Example
The following code uses the UpdateMany()
method to find all documents where the
borough
field has the value "Manhattan", then updates the borough
value in these documents to "Manhattan (north)". Because the IsUpsert
option is
set to true
, the driver inserts a new document if the query filter doesn't
match any existing documents.
var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Borough, "Manhattan"); var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Borough, "Manhattan (north)"); UpdateOptions opts = new UpdateOptions() { Comment = new BsonString("Borough updated for C# Driver Fundamentals"), IsUpsert = true }; Console.WriteLine("Updating documents..."); var result = _restaurantsCollection.UpdateMany(filter, update, opts); Console.WriteLine($"Updated documents: {result.ModifiedCount}"); Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}");
Updating documents... Updated documents: 10259 Result acknowledged? True
Note
If the preceding example used the UpdateOne()
method instead of
UpdateMany()
, the driver would update only the first of the
matched documents.
Replace Operation
You can perform a replace operation in MongoDB with the ReplaceOne()
method.
This method removes all fields (except the _id
field) from the first document that
matches the search criteria, then inserts the fields and values you specify into the
document.
Required Parameters
The ReplaceOne()
method requires the following parameters:
A query filter document, which determines which record to replace.
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.
Like in an update operation, you can use the Builders
class in the .NET/C# Driver
to create a query filter.
The following code sample uses Builders
to create a query filter that searches
for restaurants with a name
field value of "Pizza Town". The code also creates a new
Restaurant
object that will replace the first matched document.
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan", }; // Replaces the existing restaurant document with the new document return _restaurantsCollection.ReplaceOne(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 following code shows how to use the asynchronous ReplaceOneAsync()
method
or the synchronous ReplaceOne()
method to replace one document.
var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant);
var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant);
Tip
Find runnable examples that use these methods under Additional Information.
Customize the Replace Operation
The ReplaceOne()
method optionally accepts a ReplaceOptions
object as an
additional parameter, which represents options you can use to configure the replace
operation. If you don't specify any ReplaceOptions
properties, the driver does
not customize the replace operation.
The ReplaceOptions
type allows you to configure options with 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. |
| Specifies the kind of language collation to use when sorting
results. See the MongoDB server manual
for more information on collation. |
| Gets or sets the user-provided comment for the operation.
See the MongoDB server manual
for more information. |
| Gets or sets the index to use to scan for documents.
See the MongoDB server manual
for more information. |
| Specifies whether the replace operation performs an upsert operation if no
documents match the query filter.
See the MongoDB server manual
for more information. |
| Gets or sets the let document.
See the MongoDB server manual
for more information. |
Return Value
The ReplaceOne()
method returns a ReplaceOneResult
object. The ReplaceOneResult
type contains the following properties:
Property | Description |
---|---|
| Indicates whether the replace operation was acknowledged by MongoDB. |
| Indicates whether you can read the count of replaced records on the
ReplaceOneResult . |
| The number of documents that matched the query filter, regardless of
whether one was replaced. |
| The number of documents replaced by the replace operation. |
| The ID of the document that was upserted in the database, if the driver
performed an upsert. |
Example
The following code uses the ReplaceOne()
method to find the first document where the
name
field has the value "Pizza Town", then replaces this document
with a new Restaurant
document named "Food World". Because the IsUpsert
option is
set to true
, the driver inserts a new document if the query filter doesn't
match any existing documents.
var filter = Builders<Restaurant>.Filter.Eq(restaurant => restaurant.Name, "Pizza Town"); Restaurant newRestaurant = new() { Name = "Food World", Cuisine = "American", Address = new BsonDocument { {"street", "Food St"}, {"zipcode", "10003"}, }, Borough = "Manhattan", }; ReplaceOptions opts = new ReplaceOptions() { Comment = new BsonString("Restaurant replaced for .NET/C# Driver Fundamentals"), IsUpsert = true }; Console.WriteLine("Replacing document..."); var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts); Console.WriteLine($"Replaced documents: {result.ModifiedCount}"); Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}");
Replacing document... Replaced documents: 1 Result acknowledged? True
Additional Information
For runnable examples of the update and replace operations, see the following usage examples:
To learn more about creating query filters, see the Specify a Query guide.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: