Docs Menu
Docs Home
/ / /
Rust Driver
/

Find Multiple Documents

You can query for multiple documents in a collection by calling the find() method on a Collection instance.

Pass a query filter to the find() method to return documents in the collection that match the filter. If you do not include a filter, MongoDB returns all the documents in the collection.

Tip

To learn more about retrieving documents, see the Retrieve Data guide, and to learn more about creating query filters, see the Specify a Query guide.

The find() method returns a Cursor type, which you can iterate through to retrieve individual documents. To learn more about using cursors, see the Access Data by Using a Cursor guide.

This example retrieves documents that match a query filter from the restaurants collection in the sample_restaurants database. The example populates instances of the Restaurant struct with data from the retrieved documents.

The following code uses a query filter that matches documents in which the value of the cuisine field is "French".

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

use mongodb::{
bson::doc,
Client,
Collection
};
use futures::TryStreamExt;
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 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 };
#[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 mut cursor = my_coll.find(
doc! { "cuisine": "French" }
).run()?;
for result in cursor {
println!("{:?}", result?);
}
Ok(())
}

Back

Find a Document

Next

Insert a Document