查找多个文档
您可以通过调用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 }; struct Restaurant { name: String, cuisine: String, } 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 }; 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", } ...