对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

异步和同步 API

In this guide, you can learn about the Rust driver's asynchronous and synchronous APIs. This guide explains how to enable the available APIs and structure your code to use each.

Rust 驱动程序支持tokio和async-std这两个流行的异步运行时 crate。 默认情况下,驱动程序使用tokio异步运行时,但您可以通过将功能标志添加到Cargo.toml文件中的mongodb依赖项来选择特定的运行时。

该驱动程序还包括一个同步 API,适用于需要阻塞或不需要并行的使用案例。 您可以通过将功能标志添加到Cargo.toml文件中的mongodb依赖项来选择同步 API。

驱动程序默认使用tokio运行时。 您可以通过将"tokio-runtime"或"async-std-runtime"功能标志添加到mongodb依赖项中来显式选择运行时。

从以下标签页中进行选择,查看如何为每个相应的 crate 添加功能标志:

[dependencies.mongodb]
version = "2.8.2"
features = ["tokio-runtime"]

有关安装驱动程序和添加功能标志的更多信息,请参阅快速入门的下载和安装步骤。

以下代码使用tokio包中的task模块为多个数据操作创建单独的并发任务:

let client = Client::with_uri_str("<connection string>").await?;
let some_data = doc! { "title": "1984", "author": "George Orwell" };
for i in 0..5 {
let client_ref = client.clone();
let somedata_ref = some_data.clone();
task::spawn(async move {
let collection = client_ref
.database("items")
.collection::<Document>(&format!("coll{}", i));
collection.insert_one(somedata_ref, None).await
});
}

该驱动程序还提供阻塞、同步 API。 要使用同步 API,请将"sync"或"tokio-sync"功能标志添加到mongodb依赖项中。

从以下标签页中进行选择,查看如何为每个相应的 crate 添加功能标志:

[dependencies.mongodb]
version = "2.8.2"
default-features = false
features = ["sync"]

使用同步 API 时,请使用mongodb::sync模块中的类型来执行操作。 以下代码使用sync模块通过同步 API 将数据插入到集合中。 当insert_one方法在for循环内运行时,驱动程序会等待每个请求完成后再继续。

use mongodb::sync::Client;
fn main() {
let client = Client::with_uri_str("<connection string>")?;
let some_data = doc! { "title": "1984", "author": "George Orwell" };
for i in 0..5 {
let client_ref = client.clone();
let somedata_ref = some_data.clone();
let collection = client_ref
.database("items")
.collection::<Document>(&format!("coll{}", i));
collection.insert_one(somedata_ref, None);
}
}

您可以在同一应用程序中同时使用异步和同步 API。 例如,要启用两个tokio运行时,可以将tokio依赖项添加到依赖项列表中,并将"tokio-sync"标志添加到mongodb依赖项中:

[dependencies]
futures = "0.3.28"
tokio = {version = "1.32.0", features = ["full"]}
[dependencies.mongodb]
version = "2.8.2"
features = ["tokio-sync"]

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

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