Docs Menu
Docs Home
/ / /
Rust Driver
/

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.

This example retrieves a document that matches a query filter from the restaurants collection in the sample_restaurants database. The example populates a Restaurant struct with data from the retrieved document.

This example uses a query filter that matches documents in which the value of the name field is "Tompkins Square Bagels". MongoDB retrieves the first document that matches the query filter.

Select the Asynchronous or Synchronous tab to see the corresponding code for each runtime:

use mongodb::{
bson::doc,
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
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(())
}
Some(
Restaurant {
name: "Tompkins Square Bagels",
cuisine: "American",
},
)
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
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(())
}
Some(
Restaurant {
name: "Tompkins Square Bagels",
cuisine: "American",
},
)

Back

CRUD Examples