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

替换文档

在本指南中,您可以学习;了解如何使用Rust驾驶员通过 replace_one() 方法替换MongoDB集合中的文档。

替换操作会删除文档中除 _id 字段之外的所有现有字段,并用新的字段和值替换删除的字段。

注意

要学习;了解如何更新文档中的特定字段,请参阅 更新文档指南。

本指南包括以下部分:

  • 替换文档 描述了如何使用驱动程序执行替换操作

  • 修改替换行为描述了如何修改replace_one() 方法的默认行为

  • 附加信息提供了本指南中提到的类型和方法的资源和 API 文档链接

MongoDB集合中的每个文档都有一个唯一且不可变的 _id字段。如果您尝试通过替换操作更改 _id字段,驾驶员将引发 WriteError 并且不会执行更新。

您可以使用 replace_one() 方法执行替换操作。此方法会删除文档中除 _id字段之外的所有现有字段,并用您指定的新字段和值替换已删除的字段。

您还可以将选项构建器方法链接到replace_one() 方法。若要学习;了解如何修改此方法的行为,请参阅本指南的“修改替换行为”部分。

提示

您可以使用复合操作在一个操作中检索和修改数据。 要了解更多信息,请参阅复合操作指南。

replace_one() 方法采用以下参数:

  • 用于匹配要替换的文档的查询过滤

  • 替换文档,其中包含将替换现有文档的字段和值

替换文档使用以下格式:

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

如果操作成功, replace_one()方法会返回UpdateResult类型。 UpdateResult类型包含以下描述操作的属性:

属性
说明

matched_count

过滤匹配的文档数

modified_count

操作修改的文档数量

upserted_id

更新或插入文档的 _id,如果没有则为空

如果多个文档与您传递给replace_one()的查询筛选器匹配,则该方法会选择并替换第一个匹配的文档。 如果没有与查询筛选器匹配的文档,则替换操作不会进行任何更改。

本部分提供的示例演示如何使用 replace_one() 方法替换集合中的文档。

以下文档描述了某公司的一名员工:

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

此示例使用replace_one()方法将前面的文档替换为具有以下字段的文档:

  • name值为"Susan Lee"

  • role值为"Lead Consultant"

  • team_members值为[ "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

被替换的文档包含替换文档的内容和不可变的_id字段:

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

此示例替换 sample_restaurants数据库的 restaurants集合中的文档。 replace_one() 方法将 name字段值为 "Landmark Coffee Shop" 的第一个文档替换为新文档。

您可以将 restaurants集合中的文档作为 Document 类型或自定义数据类型的实例访问权限。 要指定代表集合数据的数据类型,请对突出显示的行执行以下操作:

  • 要作为BSON文档访问权限集合文档,请将 <T> 类型参数替换为 <Document>,并将 <struct or doc> 占位符替换为 replace_doc

  • 要将集合文档作为 Restaurant 结构体的实例访问权限,请将 <T> 类型参数替换为 <Restaurant>,并将 <struct or doc> 占位符替换为 replace_structRestaurant 结构体在代码文件的顶部定义。

选择 AsynchronousSynchronous标签页,查看每个运行时的相应代码:

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

您可以通过调用设立ReplaceOptions 结构体字段的选项方法来修改 replace_one() 方法的行为。

注意

设置选项

您可以通过将选项构建器方法直接链接到 replace_one() 方法调用来设立ReplaceOptions 字段。如果使用的是早期版本的驱动程序,则必须通过将选项构建器方法链接到 builder() 方法来构造 ReplaceOptions实例。然后,将选项实例作为参数传递给 replace_one()

下表描述了ReplaceOptions中可用的选项:

选项
说明

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

以下代码展示了如何通过将upsert()方法链接到replace_one()方法来设立upsert字段:

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

有关本指南中概念的更多信息,请参阅以下文档:

要进一步了解本指南所提及的方法和类型,请参阅以下 API 文档:

后退

Update Documents

在此页面上