您可以通过在 Collection 实例上调用 find_one() 方法,从集合中检索单个文档。
将查询筛选器传递给find_one()方法,以返回集合中与筛选器匹配的一份文档。 如果有多个文档与查询筛选器匹配,则此方法会根据它们在数据库中的自然顺序或根据FindOneOptions实例中指定的排序顺序返回第一个匹配的文档。
The find_one() 方法返回 Option<T> 类型,其中 T 是您用于参数化 Collection实例的类型。
要学习;了解有关检索文档的更多信息,请参阅检索数据指南。
例子
此示例从 sample_restaurants数据库的 restaurants集合中检索与查询过滤匹配的文档。 find_one() 方法返回 name字段值为 "Tompkins Square Bagels" 的第一个文档。
您可以将检索到的文档建模为 Document 类型或自定义数据类型。 要指定哪种数据类型表示集合的数据,请将突出显示的行上的 <T> 类型参数替换为以下值之一:
- <Document>:检索集合文档并将其打印为BSON文档
- <Restaurant>:检索集合文档并将其打印为- Restaurant结构的实例,该结构在代码顶部定义
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码:
use mongodb::{      bson::doc,     Client,     Collection }; 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 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 }; 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 Document Result 或 Restaurant Struct Result标签页,根据集合的类型参数查看相应的代码输出:
Some(    Document({       "_id": ObjectId(             "...",       ),       ...       "name": String(             "Tompkins Square Bagels",       ),       ...    }), ) 
Some(    Restaurant {       name: "Tompkins Square Bagels",       cuisine: "American",    }, )