您可以通过在 Collection实例上调用 find_one() 方法,从集合中检索单个文档。
Pass a query filter to the find_one() method to return one document in the collection that matches the filter. If multiple documents match the query filter, this method returns the first matching document according to their natural order in the database or according to the sort order specified in a FindOneOptions instance.
The find_one() 方法返回 Option<T> 类型,其中 T 是您用于参数化 Collection实例的类型。
如需了解有关检索文档的更多信息,请参阅“检索数据”指南。
例子
此示例从sample_restaurants数据库的restaurantscollection中检索与查询筛选器匹配的文档。该示例使用检索到的文档中的数据填充Restaurant结构体。
此示例使用的查询筛选器匹配name字段值为"Tompkins Square Bagels"的文档。 MongoDB 检索与查询筛选器匹配的第一个文档。
选择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?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" }, None ).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)?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" }, None )?; println!("{:#?}", result); Ok(()) }