Retrieve Data
On this page
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 presents the sample data that is used by the read operation examples
Find Operations describes how to use the driver to execute find operations
Aggregation Operations describes how to use the driver to execute aggregation operations
Additional Information provides links to resources and API documentation for types and methods mentioned in this guide
Sample Data for Examples
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:
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 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.
To learn more about specifying a query, see the Specify a Query 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.
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 guide. Type: Collation Default: None |
hint | The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: Hint Default: None |
projection | The projection to use when returning results. 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
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 Returned Results.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
in the Server manual glossary. To learn more about how to use the
sort() builder method, see Sort Results.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 and FindOneOptions.
Examples
The following sections contain examples that use the find()
and
findOne()
methods to retrieve sample documents that match filter
criteria.
find() Example
This example performs the following actions:
Calls the
find()
methodPasses a query filter to
find()
that matches documents where the value ofunit_price
is less than12.00
and the value ofcategory
is not"kitchen"
Chains the
sort()
method tofind()
to sort matched documents byunit_price
in descending order
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); }
Inventory { item: "watering can", category: "garden", unit_price: 11.99 } Inventory { item: "candle", category: "decor", unit_price: 2.89 }
find_one() Example
This example performs the following actions:
Calls the
find_one()
methodPasses a query filter to
find_one()
that matches documents where the value ofunit_price
is less than or equal to20.00
Chains the
skip()
method tofind_one()
to skip the first two matched documents
let result = my_coll .find_one(doc! { "unit_price": doc! { "$lte": 20.00 } }) .skip(2) .await?; println!("{:#?}", result);
Some( Inventory { item: "watering can", category: "garden", unit_price: 11.99, }, )
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 guide.
The method returns the resulting documents in a Cursor
type. If
your aggregation pipeline does not contain a $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 guide. Type: Collation Default: None |
hint | The index to use for the operation. To learn more about
indexes, see 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
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 in the
Server manual. Type: WriteConcern |
For a full list of settings, see the API documentation for AggregateOptions.
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 theunit_price
field for each value of thecategory
field$sort
stage to order results byavg_price
in ascending order
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); }
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:
To learn more about the operations in this guide, see the following documentation:
Specify a Query guide
Aggregation guide
Sort Results guide
Skip Returned Results guide
API Documentation
To learn more about the methods and types mentioned in this guide, see the following API documentation: