Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
Rust 驱动程序
/

查找多个文档

您可以通过在 Collection实例上调用 find() 方法来查询集合中的多个文档。

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

提示

要学习;了解有关检索文档的更多信息,请参阅《 检索数据》指南,要学习;了解有关创建查询筛选器的更多信息,请参阅《指定查询》指南。

find()方法返回一个 Cursor 类型,您可以遍历该类型来检索单个文档。要学习;了解有关使用游标的更多信息,请参阅《使用游标访问数据》指南。

此示例从数据库sample_restaurants的collectionrestaurants中检索与查询筛选器匹配的文档。该示例使用检索到的文档中的数据填充Restaurant结构的实例。

以下代码使用查询筛选器来匹配字段的值为cuisine "French"的文档。

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

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?;
let my_coll: Collection<Restaurant> = client
.database("sample_restaurants")
.collection("restaurants");
let mut cursor = my_coll.find(
doc! { "cuisine": "French" },
None
).await?;
while let Some(doc) = cursor.try_next().await? {
println!("{:?}", doc);
}
Ok(())
}
// Results truncated
...
Restaurant { name: "Cafe Un Deux Trois", cuisine: "French" }
Restaurant { name: "Calliope", cuisine: "French" }
...
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)?;
let my_coll: Collection<Restaurant> = client
.database("sample_restaurants")
.collection("restaurants");
let mut cursor = my_coll.find(
doc! { "cuisine": "French" },
None
)?;
for result in cursor {
println!("{:?}", result?);
}
Ok(())
}
// Results truncated
...
Restaurant { name: "Cafe Un Deux Trois", cuisine: "French" }
Restaurant { name: "Calliope", cuisine: "French" }
...

后退

查找一个