Replace a Document
You can replace one document with another by using the ReplaceOne()
synchronous method
or the ReplaceOneAsync()
asynchronous method on a collection object.
Example
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.
// 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", }; // Asynchronously replaces the existing restaurant document with the new document return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);
For a fully runnable example of the ReplaceOneAsync()
operation, see the
ReplaceOneAsync code sample.
// 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);
For a fully runnable example of the ReplaceOne()
operation, see the
ReplaceOne code sample.
Expected Result
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.
Additional Information
To learn more about replacing documents, see the Replace Operation guide.
To learn more about using builders, see Operations with Builders.