For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Replace a Document

You can replace a document in a collection by calling the replace_one() method on a Collection instance.

Pass the following parameters to the replace_one() method:

  • Query filter, which specifies the criteria to match

  • Replacement document, which contains the fields and values that will replace the first matched document

The replace_one() method returns an UpdateResult type that contains information about the results of the replace operation, such as the number of modified documents.

To learn more about the replace_one() method, see the Replace a Document section of the Modify Documents guide.

This example replaces a document in the restaurants collection of the sample_restaurants database. The example uses a Restaurant struct that has name, borough, and cuisine fields to model documents in the collection.

The following code replaces a document in which the value of the name field is "Landmark Coffee Shop" with a new document. MongoDB replaces the first document that matches the query filter.

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use std::env;use mongodb::{ bson::doc, Client, Collection };use serde::{ Deserialize, Serialize }; #[derive(Serialize, Deserialize, Debug)]struct Restaurant { borough: String, cuisine: String, name: String,} #[tokio::main]async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "name": "Landmark Coffee Shop" }; let replacement = Restaurant { borough: "Brooklyn".to_string(), cuisine: "Café/Coffee/Tea".to_string(), name: "Harvest Moon Café".to_string(), }; let res = my_coll.replace_one(filter, replacement, None).await?; println!("Replaced documents: {}", res.modified_count); Ok(())}
Rate this page