Docs Menu

Docs HomeC#/.NET

Update a Document

On this page

  • Examples
  • 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 examples on this page 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 camel-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.

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.

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 Change Documents guide.

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

←  Insert Multiple DocumentsUpdate Many Documents →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.