Docs Menu

Docs HomeC#/.NET

Replace a Document

On this page

  • Example
  • Expected Result
  • Additional Information
  • API Documentation

You can replace one document with another by using the ReplaceOne() synchronous method or the ReplaceOneAsync() asynchronous method on a collection object.

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 code replaces the first document in the restaurants collection that has a value of "Pizza" in the cuisine field. After the replacement, this document will have a name field with a value of "Mongo's Pizza" and new values for the address and borough fields.

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

Running either of the preceding full examples prints the following results:

First pizza restaurant before replacement: J&V Famous Pizza
Restaurants modified by replacement: 1
First pizza restaurant after replacement: Mongo's Pizza
Resetting sample data...done.

To learn more about replacing documents, see the Replace Operation guide.

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

←  Update Many DocumentsDelete a Document →
Share Feedback
© 2023 MongoDB, Inc.

About

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