文档菜单
文档首页
/ / /
Rust 驱动
/

查找文档

本页

  • 示例
  • 输出

您可以通过调用find_one() 方法从一个集合中检索单个文档。Collection 实例。

将查询过滤器传递给 find_one() 方法以返回与过滤器匹配的集合中的单个文档。如果多个文档与查询过滤器匹配,则该方法根据它们的自然顺序或根据 FindOneOptions 实例中指定的排序顺序返回第一个匹配的文档。

find_one() 方法返回一个Option<T> 类型,其中 T 是您用其参数化 Collection 实例的类型。

要了解更多关于检索文档的信息,请参阅检索数据 指南。

本示例从sample_restaurants数据库中的restaurants集合检索与查询过滤器匹配的文档。使用find_one()方法返回第一个name字段值为"Tompkins Square Bagels"的文档。

您可以将检索到的文档建模为Document类型或自定义数据类型。要指定哪种数据类型代表集合的数据,请将高亮行上的<T>类型参数替换为以下值之一

  • <Document>:以BSON文档的形式检索并打印集合文档

  • <Restaurant>:以在代码顶部定义的Restaurant结构体的实例的形式检索并打印集合文档

选择异步同步选项卡以查看每个运行时对应的代码

use mongodb::{
bson::doc,
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: 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 result = my_coll.find_one(
doc! { "name": "Tompkins Square Bagels" }
).await?;
println!("{:#?}", result);
Ok(())
}
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: 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 result = my_coll.find_one(
doc! { "name": "Tompkins Square Bagels" }
).run()?;
println!("{:#?}", result);
Ok(())
}

选择BSON文档结果餐厅结构体结果选项卡,查看根据您的集合类型参数对应的代码输出

Some(
Document({
"_id": ObjectId(
"...",
),
...
"name": String(
"Tompkins Square Bagels",
),
...
}),
)
Some(
Restaurant {
name: "Tompkins Square Bagels",
cuisine: "American",
},
)

返回

CRUD 示例