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

Update a Document

On this page

  • Example
  • Expected Result
  • More Information
  • API Documentation

You can update a single document using the UpdateOne() method on a MongoCollection object. This method requires a query filter, which specifies which document to update, and an update statement, which specifies the changes the driver should make to the first document matching the query filter.

Note

The UpdateOne() method updates only the first document that matches the filter. To update more than one document, use the UpdateMany() method.

Tip

You can pass an instance of UpdateOptions to the UpdateOne() method in order to customize its behavior.

The following example uses Builders to update the name of the first document named "Bagels N Buns" in the restaurants collection to "2 Bagels 2 Buns".

Select the Asynchronous or Synchronous tab to see the corresponding code.

// Creates a filter for all documents with a "name" of "Bagels N Buns"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
// Creates instructions to update the "name" field of the first document
// that matches the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
// Updates the first document that has a "name" value of "Bagels N Buns"
return await _restaurantsCollection.UpdateOneAsync(filter, update);

For a fully runnable example of the UpdateOneAsync() operation, see the UpdateOneAsync Example.

// Creates a filter for all documents with a "name" of "Bagels N Buns"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Name, "Bagels N Buns");
// Creates instructions to update the "name" field of the first document
// that matches the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
// Updates the first document that has a "name" value of "Bagels N Buns"
return _restaurantsCollection.UpdateOne(filter, update);

For a fully runnable example of the UpdateOneAsync() operation, see the UpdateOne Example.

After running either of the preceding full examples, each call to UpdateOne() writes the following to the console:

Updated documents: 1

Tip

UpdateOne() returns an UpdateResult object.

To learn more about updating documents, see the Update One guide.

To learn more about using builders, see Operations with Builders.

Back

Insert Multiple Documents