Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

Replace Documents

In this guide, you can learn how to use the Rust driver to replace documents in a MongoDB collection by using the replace_one() method.

Replace operations remove all existing fields of a document except for the _id field and substitute the removed fields with new fields and values.

Note

To learn how to update specific fields in documents, see the Update Documents guide.

This guide includes the following sections:

  • Replace a Document describes how to use the driver to execute replace operations

  • Modify Replace Behavior describes how to modify the default behavior of the replace_one() method

  • Additional Information provides links to resources and API documentation for types and methods mentioned in this guide

Each document in a MongoDB collection has a unique and immutable _id field. If you attempt to change the _id field through a replace operation, the driver raises a WriteError and performs no updates.

You can perform a replace operation with the replace_one() method. This method removes all existing fields of a document except for the _id field and substitutes the removed fields with new fields and values that you specify.

You can also chain option builder methods to the replace_one() method. To learn about modifying the behavior of this method, see the Modify Replace Behavior section of this guide.

Tip

You can retrieve and modify data in one action by using compound operations. To learn more, see the guide on Compound Operations.

The replace_one() method takes the following parameters:

  • Query filter to match the document to replace

  • Replacement documents that contains the fields and values that will replace an existing document

Replacement documents use the following format:

doc! { "<field>": <value>, "<field>": <value>, ... }

The replace_one() method returns an UpdateResult type if the operation is successful. The UpdateResult type contains the following properties that describe the operation:

Property
Description

matched_count

The number of documents matched by the filter

modified_count

The number of documents modified by the operation

upserted_id

The _id of the upserted document, or empty if there is none

If multiple documents match the query filter you pass to replace_one(), the method selects and replaces the first matched document. If no documents match the query filter, the replace operation makes no changes.

This section provides examples that demonstrate how to use the replace_one() method to replace documents in a collection.

The following document describes an employee of a company:

{
"_id": ObjectId('4501'),
"name": "Matt DeGuy",
"role": "Consultant",
"team_members": [ "Jill Gillison", "Susan Lee" ]
}

This example uses the replace_one() method to replace the preceding document with one that has the following fields:

  • A name value of "Susan Lee"

  • A role value of "Lead Consultant"

  • A team_members value of [ "Jill Gillison" ]

let replace_doc = doc! {
"name": "Susan Lee",
"role": "Lead Consultant",
"team_members": vec! [ "Jill Gillison" ]
};
let res = my_coll
.replace_one(doc! { "name": "Matt DeGuy" }, replace_doc)
.await?;
println!(
"Matched documents: {}\nModified documents: {}",
res.matched_count, res.modified_count
);
Matched documents: 1
Modified documents: 1

The replaced document contains the contents of the replacement document and the immutable _id field:

{
"_id": ObjectId('4501'),
"name": "Susan Lee",
"role": "Lead Consultant",
"team_members": [ "Jill Gillison" ]
}

This example replaces a document in the restaurants collection of the sample_restaurants database. The replace_one() method replaces the first document in which the value of the name field is "Landmark Coffee Shop" with a new document.

You can access the documents in the restaurants collection as instances of the Document type or a custom data type. To specify which data type represents the collection's data, perform the following actions on the highlighted lines:

  • To access collection documents as BSON documents, replace the <T> type parameter with <Document> and the <struct or doc> placeholder with replace_doc.

  • To access collection documents as instances of the Restaurant struct, replace the <T> type parameter with <Restaurant> and the <struct or doc> placeholder with replace_struct. The Restaurant struct is defined at the top of the code file.

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?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter = doc! { "name": "Landmark Coffee Shop" };
let replace_doc = doc! {
"borough": "Brooklyn",
"cuisine": "Café/Coffee/Tea",
"name": "Harvest Moon Café",
};
let replace_struct = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
// Replace <struct or doc> with the replace_struct or replace_doc variable
let res = my_coll.replace_one(filter, <struct or doc>).await?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1
use std::env;
use mongodb::{ bson::doc, sync::{ Client, Collection } };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter = doc! { "name": "Landmark Coffee Shop" };
let replace_doc = doc! {
"borough": "Brooklyn",
"cuisine": "Café/Coffee/Tea",
"name": "Harvest Moon Café",
};
let replace_struct = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
// Replace <struct or doc> with the replace_struct or replace_doc variable
let res = my_coll.replace_one(filter, <struct or doc>).run()?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1

You can modify the behavior of the replace_one() method by calling options methods that set ReplaceOptions struct fields.

Note

Setting Options

You can set ReplaceOptions fields by chaining option builder methods directly to the replace_one() method call. If you're using an earlier version of the driver, you must construct a ReplaceOptions instance by chaining option builder methods to the builder() method. Then, pass your options instance as a parameter to replace_one().

The following table describes the options available in ReplaceOptions:

Option
Description

array_filters

The set of filters specifying the array elements to which the update applies.

Type: Vec<Document>

bypass_document_validation

If true, allows the driver to perform a write that violates document-level validation. To learn more about validation, see the guide on Schema Validation.

Type: bool
Default: false

upsert

If true, the operation inserts a document if no documents match the query filter.

Type: bool

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

The index to use for the operation.

Type: Hint
Default: None

write_concern

The write concern for the operation. If you don't set this option, the operation inherits the write concern set for the collection. To learn more about write concerns, see Write Concern in the MongoDB Server manual.

Type: WriteConcern

let_vars

A map of parameters and values. These parameters can be accessed as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.

Type: Document

comment

An arbitrary Bson value tied to the operation to trace it through the database profiler, currentOp, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.

Type: Bson
Default: None

The following code shows how to set the upsert field by chaining the upsert() method to the replace_one() method:

let res = my_coll
.replace_one(filter_doc, replace_doc)
.upsert(true)
.await?;

For more information about the concepts in this guide, see the following documentation:

To learn more about the methods and types mentioned in this guide, see the following API documentation:

Back

Update Documents

On this page