> This page location: /docs.md > /docs/drivers.md > /docs/languages/rust.md > /docs/drivers/rust/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: find-async, find-sync, find-output-bson, find-output-restaurant, find-one-async, find-one-sync, find-one-output-bson, find-one-output-restaurant
-->

# Find Documents

## Overview

In this guide, you can learn how to retrieve data from your MongoDB collections using **read operations**. Read operations are commands that retrieve documents from the server.

There are two types of read operations:

- Find operations, which allow you to retrieve documents from your collections

- Aggregation operations, which allow you to transform the data in your collections

This guide includes the following sections:

- [Sample Data for Examples](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-retrieve-sample-data) presents the sample data that is used by the read operation examples

- [Find Operations](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-retrieve-find) describes how to use the driver to execute find operations

- [Aggregation Operations](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-retrieve-aggregation) describes how to use the driver to execute aggregation operations

- [Additional Information](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-crud-retrieve-addtl-info) provides links to resources and API documentation for types and methods mentioned in this guide

## Sample Data for Examples

Several of the examples in this guide use the following sample documents. Each document represents an item in a store's inventory and contains information about its categorization and unit price:

```rust
let docs = vec![
    Inventory {
        item: "candle".to_string(),
        category: "decor".to_string(),
        unit_price: 2.89,
    },
    Inventory {
        item: "blender".to_string(),
        category: "kitchen".to_string(),
        unit_price: 38.49,
    },
    Inventory {
        item: "placemat".to_string(),
        category: "kitchen".to_string(),
        unit_price: 3.19,
    },
    Inventory {
        item: "watering can".to_string(),
        category: "garden".to_string(),
        unit_price: 11.99,
    },
];
```

To learn how to insert this data into a collection, see the [Insert Documents](https://www.mongodb.com/docs/drivers/rust/current/crud/insert.md#std-label-rust-insert-guide) guide.

## Find Operations

Use find operations to retrieve data from MongoDB. Find operations consist of the `find()` and `find_one()` methods.

### Find All Matching Documents

To find *all the documents* that match your criteria, use the `find()` method. This method takes a query filter as a parameter. A query filter consists of the fields and values that form criteria for documents to match.

The method returns a `Cursor` type that you can iterate through to retrieve any documents that match the filter criteria.

To see an example that uses this method to retrieve data, see the [find() example.](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-find-example)

To learn more about specifying a query, see the [Specify a Query](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-query.md#std-label-rust-query-guide) guide.

### Find One Document

To find *the first document* that matches your criteria, use the `find_one()` method. This method takes a query filter as a parameter. A query filter consists of the fields and values that form criteria for documents to match.

If a document matches the filter criteria, the method returns a `Result<Option<T>>` type with a value of `Some`. If no documents match the filter criteria, `find_one()` returns a `Result<Option<T>>` type with a value of `None`.

To see an example that uses this method to retrieve data, see the [find\_one() example.](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-find-one-example)

### Modify Find Behavior

You can modify the behavior of the `find()` method by chaining `FindOptions` option builder methods to `find()`, and you can modify the behavior of the `find_one()` method by chaining `FindOneOptions` option builder methods to `find_one()`.

The following table describes commonly used `FindOptions` and `FindOneOptions` fields that you can set by calling their corresponding builder methods:

| Field | Description |
| --- | --- |
| `collation` | The collation to use when sorting results. To learn more about collations, see the [Collations](https://www.mongodb.com/docs/drivers/rust/current/aggregation/collations.md#std-label-rust-collations) guide.Type: `Collation`Default: `None` |
| `hint` | The index to use for the operation. To learn more about indexes, see [Indexes](https://www.mongodb.com/docs/manual/indexes/) in the Server manual.Type: `Hint`Default: `None` |
| `projection` | The projection to use when returning results. To learn more about projections, see the [Specify Fields to Return](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-fields.md#std-label-rust-specify-fields) guide.Type: `Document`Default: `None` |
| `read_concern` | The read concern to use for the find operation. If you don't set this option, the operation inherits the read concern set for the collection. To learn more about read concerns, see [Read Concern](https://www.mongodb.com/docs/manual/reference/read-concern/) in the Server manual.Type: `ReadConcern` |
| `skip` | The number of documents to skip when returning results. To learn more about how to use the `skip()` builder method, see [Skip](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-documents.md#std-label-rust-skip-guide).Type: `u64`Default: `None` |
| `sort` | The sort to use when returning results. By default, the driver returns documents in their natural order, or as they appear in the database. To learn more, see [natural order](https://www.mongodb.com/docs/manual/reference/glossary/#std-term-natural-order) in the Server manual glossary. To learn more about how to use the `sort()` builder method, see [Sort](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-documents.md#std-label-rust-sort-guide).Type: `Document`Default: `None` |

**Note: Setting Options**

You can set `FindOptions` and `FindOneOptions` fields by chaining option builder methods directly to the find operation method call. If you're using an earlier version of the driver, you must construct a `FindOptions` or `FindOneOptions` instance by chaining option builder methods to the `builder()` method. Then, pass your options instance as a parameter to `find()` or `find_one()`.

For a full list of settings you can specify for each type, see the API documentation for [FindOptions](https://docs.rs/mongodb/3.10.1/mongodb/options/struct.FindOptions.html) and [FindOneOptions.](https://docs.rs/mongodb/3.10.1/mongodb/options/struct.FindOneOptions.html)

## Find Examples

The following sections contain examples that use the `find()` and `find_one()` methods to retrieve sample documents that match filter criteria.

### find() Example

This example performs the following actions:

- Calls the `find()` method

- Passes a query filter to `find()` that matches documents where the value of `unit_price` is less than `12.00` and the value of `category` is not `"kitchen"`

- Chains the `sort()` method to `find()` to sort matched documents by `unit_price` in descending order

```rust
let mut cursor = my_coll
    .find(doc! { "$and": vec!
    [
        doc! { "unit_price": doc! { "$lt": 12.00 } },
        doc! { "category": doc! { "$ne": "kitchen" } }
    ] })
    .sort(doc! { "unit_price": -1 })
    .await?;

while let Some(result) = cursor.try_next().await? {
    println!("{:?}", result);
}

```

**Output:**

```console
Inventory { item: "watering can", category: "garden", unit_price: 11.99 }
Inventory { item: "candle", category: "decor", unit_price: 2.89 }
```

### Full File Example: Find Documents

This example retrieves documents that match a query filter from the `restaurants` collection in the `sample_restaurants` database. The `find()` method returns all documents in which the value of the `cuisine` field is `"French"`.

You can model each 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 the `Restaurant` struct, defined at the top of the code

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

### Asynchronous

```rust
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?;

    // Replace <T> with the <Document> or <Restaurant> type parameter
    let my_coll: Collection<T> = 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(())
}



```

#### Output

Select the BSON Document Results or Restaurant Struct Results tab to see the corresponding code output based on your collection's type parameter:

### BSON Document Results

```none
...
Some(
   Document({
      "_id": ObjectId(
            "...",
      ),
      ...
      "name": String(
            "Cafe Un Deux Trois",
      ),
      ...
   }),
),
Some(
   Document({
      "_id": ObjectId(
            "...",
      ),
      ...
      "name": String(
            "Calliope",
      ),
      ...
   }),
)
...
```

### Load a Query From a File Example

You can store a query filter in a JSON file and load it at runtime. This approach lets you share query definitions between your Rust application and external tools, such as the MongoDB Shell (`mongosh`).

**Tip: Serde JSON Dependency**

Before you load a query from a file, add the `serde_json` dependency by running the following command from your project root:

```sh
cargo add serde_json
```

First, create a JSON file that contains your query filter. The following sample `query.json` file contains a comparison query filter that matches documents in which the `category` field value is `"kitchen"`:

```json
{ "category": "kitchen" }

```

To load this file into your Rust application, read the file by using the `std::fs::read_to_string()` method. Then, call `serde_json::from_str()` to parse the JSON string into a `Document` instance. Because `Document` implements the `serde::Deserialize` trait, you can deserialize it directly from a JSON string.

The following example reads a query filter from the `query.json` file and passes it to the `find()` method:

```rust
let json = std::fs::read_to_string("query.json")
    .expect("failed to read query.json");
let filter: Document = serde_json::from_str(&json)
    .expect("query.json contains invalid JSON");
let mut cursor = my_coll.find(filter).await?;
while let Some(doc) = cursor.try_next().await? {
    println!("{:?}", doc);
}
```

**Output:**

```console
Inventory { item: "blender", category: "kitchen", unit_price: 38.49 }
Inventory { item: "placemat", category: "kitchen", unit_price: 3.19 }
```

### find\_one() Example

This example performs the following actions:

- Calls the `find_one()` method

- Passes a query filter to `find_one()` that matches documents where the value of `unit_price` is less than or equal to `20.00`

- Chains the `skip()` method to `find_one()` to skip the first two matched documents

```rust
let result = my_coll
    .find_one(doc! { "unit_price": doc! { "$lte": 20.00 } })
    .skip(2)
    .await?;

println!("{:#?}", result);
```

**Output:**

```console
Some(
    Inventory {
        item: "watering can",
        category: "garden",
        unit_price: 11.99,
    },
)
```

### Full File Example: Find a Document

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 the `Restaurant` struct, defined at the top of the code

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

### Asynchronous

```rust
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?;

    // 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(())
}


```

#### Output

Select the BSON Document Result or Restaurant Struct Result tab to see the corresponding code output based on your collection's type parameter:

### BSON Document Result

```none
Some(
   Document({
      "_id": ObjectId(
            "...",
      ),
      ...
      "name": String(
            "Tompkins Square Bagels",
      ),
      ...
   }),
)
```

## Aggregation Operations

Use aggregation operations to retrieve and transform data from your collections. You can perform aggregation operations by using the `aggregate()` method.

### Aggregate Document Data

The `aggregate()` method takes an **aggregation pipeline** as a parameter. An aggregation pipeline includes one or more **stages** that specify how to transform data. A stage includes an aggregation operator (prefixed with a `$`) and any required parameters for that operator.

To learn more about aggregations and view aggregation examples, see the [Aggregation](https://www.mongodb.com/docs/drivers/rust/current/aggregation.md#std-label-rust-aggregation) guide.

The method returns the resulting documents in a `Cursor` type. If your aggregation pipeline does not contain a [$match](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match/) stage, the pipeline processes all the documents in the collection.

### Modify Aggregation Behavior

You can modify the behavior of the `aggregate()` method by chaining `AggregateOptions` option builder methods to `aggregate()`.

The following table describes commonly used `AggregateOptions` fields that you can set by calling their corresponding builder methods:

| Field | Description |
| --- | --- |
| `allow_disk_use` | Enables writing to temporary files. If `true`, aggregation stages can write data to the `_tmp` subdirectory in the `dbPath` directory.Type: `bool`Default: `false` |
| `batch_size` | Specifies the maximum number of documents the server returns per cursor batch. This option sets the number of documents the cursor keeps in memory rather than the number of documents the cursor returns.Type: `u32`Default: `101` documents initially, `16 MB` maximum for subsequent batches |
| `collation` | The collation to use when sorting results. To learn more about collations, see the [Collations](https://www.mongodb.com/docs/drivers/rust/current/aggregation/collations.md#std-label-rust-collations) guide.Type: `Collation`Default: `None` |
| `hint` | The index to use for the operation. To learn more about indexes, see [Indexes](https://www.mongodb.com/docs/manual/indexes/) in the Server manual.Type: `Hint`Default: `None` |
| `read_concern` | The read concern to use for the find operation. If you don't set this option, the operation inherits the read concern set for the collection. To learn more about read concerns, see [Read Concern](https://www.mongodb.com/docs/manual/reference/read-concern/) in the Server manual.Type: `ReadConcern` |
| `write_concern` | The write concern for the operation. If you don't set this option, the operation inherits the write concern set for the collection. To learn more about write concerns, see [Write Concern](https://www.mongodb.com/docs/manual/reference/write-concern/) in the Server manual.Type: `WriteConcern` |

For a full list of settings, see the API documentation for [AggregateOptions.](https://docs.rs/mongodb/3.10.1/mongodb/options/struct.AggregateOptions.html)

### Example

This example shows how to call the `aggregate()` method with a pipeline that contains the following stages:

- `$group` stage to calculate the average of the `unit_price` field for each value of the `category` field

- `$sort` stage to order results by `avg_price` in ascending order

```rust
let pipeline = vec![
    doc! { "$group": doc! { "_id" : doc! {"category": "$category"} ,
    "avg_price" : doc! { "$avg" : "$unit_price" } } },
    doc! { "$sort": { "_id.avg_price" : 1 } },
];

let mut cursor = my_coll.aggregate(pipeline).await?;
while let Some(result) = cursor.try_next().await? {
    println!("{:?}", result);
}
```

**Output:**

```console
Document({"_id": Document({"category": String("decor")}), "avg_price": Double(2.890000104904175)})
Document({"_id": Document({"category": String("kitchen")}), "avg_price": Double(20.840000867843628)})
Document({"_id": Document({"category": String("garden")}), "avg_price": Double(11.989999771118164)})
```

## Additional Information

For runnable examples of the find operations, see the following usage examples:

- [Full File Example: Find a Document](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-find-one-usage)

- [Full File Example: Find Documents](https://www.mongodb.com/docs/drivers/rust/current/crud/query/retrieve.md#std-label-rust-find-usage)

To learn more about the operations in this guide, see the following documentation:

- [Specify a Query](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-query.md#std-label-rust-query-guide) guide

- [Access Data by Using a Cursor](https://www.mongodb.com/docs/drivers/rust/current/crud/query/cursor.md#std-label-rust-cursor-guide) guide

- [Aggregation](https://www.mongodb.com/docs/drivers/rust/current/aggregation.md#std-label-rust-aggregation) guide

- [Sort](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-documents.md#std-label-rust-sort-guide) guide

- [Skip](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-documents.md#std-label-rust-skip-guide) guide

- [Limit](https://www.mongodb.com/docs/drivers/rust/current/crud/query/specify-documents.md#std-label-rust-limit-guide) guide

### API Documentation

To learn more about the methods and types mentioned in this guide, see the following API documentation:

- [find\_one()](https://docs.rs/mongodb/3.10.1/mongodb/struct.Collection.html#method.find_one)

- [find()](https://docs.rs/mongodb/3.10.1/mongodb/struct.Collection.html#method.find)

- [FindOptions](https://docs.rs/mongodb/3.10.1/mongodb/options/struct.FindOptions.html)

- [FindOneOptions](https://docs.rs/mongodb/3.10.1/mongodb/options/struct.FindOneOptions.html)

- [Cursor](https://docs.rs/mongodb/3.10.1/mongodb/struct.Cursor.html)

- [aggregate()](https://docs.rs/mongodb/3.10.1/mongodb/struct.Collection.html#method.aggregate)

- [AggregateOptions](https://docs.rs/mongodb/3.10.1/mongodb/options/struct.AggregateOptions.html)
