Lesson 4: Updating Documents in C# Applications / Learn
Updating Documents in C# Applications
Review the following code, which demonstrates how to update documents in MongoDB with C#.
Update a Single Document
The following example demonstrates how to update a single document. First, create a filter definition with the .Filter method on the Builders class, which returns the account with an AccountId equal to “MDB951086017”. Next, create an update definition that will set the balance to 5000. Finally, use the UpdateOne() method to update the document.
var filter = Builders<Account>
.Filter
.Eq(a => a.AccountId, "MDB951086017");
var update = Builders<Account>
.Update
.Set(a=>a.Balance, 5000);
var result = accountCollection.UpdateOne(filter, update);
Console.WriteLine(result.ModifiedCount);
Update a Single Document Asynchronously
The UpdateOneAsync() command updates a single document in the collection asynchronously. For example:
var result = await accountsCollection.UpdateOneAsync(filter, update);
Console.WriteLine(result.ModifiedCount);
Update Multiple Documents
Use the UpdateMany() method to update multiple documents in a single operation. Just like the UpdateOne() method, the UpdateMany() method accepts a query and an update. Here's an example:
var filter = Builders<Account>
.Filter
.Eq(a => a.AccountType, "checking");
var update = Builders<Account>
.Update
.Inc(a => a.Balance, 5);
var updateResult = accountCollection
.UpdateMany(filter, update);
Console.WriteLine(updateResult.ModifiedCount);
Update Multiple Documents Asynchronously
The UpdateManyAsync() command updates multiple documents in the collection asynchronously. For example:
var filter = Builders<BsonDocument>
.Filter
.Lt("balance", 500);
var update = Builders<BsonDocument>
.Update
.Inc("balance", 10);
var result = await accountsCollection
.UpdateManyAsync(filter, update);
Console.WriteLine(result.ModifiedCount);