您可以通过在 Collection
实例上调用 find() 方法来查询集合中的多个文档。
将查询筛选器传递给find()
方法,以返回集合中与筛选器匹配的文档。 如果不包含筛选器,MongoDB 将返回collection中的所有文档。
find()
方法返回一个 Cursor 类型,您可以遍历该类型来检索单个文档。要学习;了解有关使用游标的更多信息,请参阅《使用游标访问数据》指南。
例子
此示例从数据库sample_restaurants
的collectionrestaurants
中检索与查询筛选器匹配的文档。该示例使用检索到的文档中的数据填充Restaurant
结构的实例。
以下代码使用查询筛选器来匹配字段的值为cuisine
"French"
的文档。
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use mongodb::{ bson::doc, Client, Collection }; use futures::TryStreamExt; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } 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 }; 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" } ...