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

查找多个文档

本页内容

  • 示例
  • 输出

您可以通过调用find() 方法用于Collection

实例。

将查询过滤器传递给 find() 方法,以返回与过滤器匹配的集合中的文档。如果不包括过滤器,MongoDB 将返回集合中的所有文档。

提示

要了解更多关于检索文档的信息,请参阅检索数据 指南,以及要了解更多关于创建查询过滤器的信息,请参阅 指定查询 指南。

find() 方法返回一个 Cursor 类型,您可以通过它迭代以检索单个文档。要了解更多关于使用游标的信息,请参阅 通过游标访问数据 指南。

本例从sample_restaurants数据库中的restaurants集合中检索与查询过滤器匹配的文档。find()方法返回所有cuisine字段的值为"French"的文档。

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

  • <Document>:检索并打印集合文档作为BSON文档

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

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

use mongodb::{
bson::doc,
Client,
Collection
};
use futures::TryStreamExt;
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 mut cursor = my_coll.find(
doc! { "cuisine": "French" }
).await?;
while let Some(doc) = cursor.try_next().await? {
println!("{:#?}", doc);
}
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 mut cursor = my_coll.find(
doc! { "cuisine": "French" }
).run()?;
for result in cursor {
println!("{:#?}", result?);
}
Ok(())
}

选择BSON文档结果Restaurant结构体结果选项卡,以查看基于您的集合类型参数的相应代码输出

...
Some(
Document({
"_id": ObjectId(
"...",
),
...
"name": String(
"Cafe Un Deux Trois",
),
...
}),
),
Some(
Document({
"_id": ObjectId(
"...",
),
...
"name": String(
"Calliope",
),
...
}),
)
...
...
Restaurant {
name: "Cafe Un Deux Trois",
cuisine: "French",
}
Restaurant {
name: "Calliope",
cuisine: "French",
}
...

返回

查找单个文档

本页内容