Find a Document
You can retrieve a single document from a collection by calling the find_one() method on a Collection
instance.
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()
method returns an Option<T>
type, where T
is the type with which you parameterized your Collection
instance.
To learn more about retrieving documents, see the Retrieve Data guide.
Example
This example retrieves a document that matches a query filter from the restaurants
collection in the sample_restaurants
database. The find_one()
method returns the
first document in which the value of the name
field is "Tompkins Square Bagels"
.
You can model the retrieved document as a Document
type or a custom data type. To specify
which data type represents the collection's data, replace the <T>
type parameter on the
highlighted line with one of the following values:
<Document>
: Retrieves and prints collection documents as BSON documents<Restaurant>
: Retrieves and prints collection documents as instances of theRestaurant
struct, defined at the top of the code
Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:
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(()) }
Output
Select the BSON Document Result or Restaurant Struct Result tab to see the corresponding code output based on your collection's type parameter:
Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Tompkins Square Bagels", ), ... }), )
Some( Restaurant { name: "Tompkins Square Bagels", cuisine: "American", }, )