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, } ];
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 find()
by passing
a FindOptions
instance as a parameter, and you can modify the
behavior of find_one()
by passing a FindOneOptions
instance.
To use default values for each setting, specify the value None
as
the options parameter.
The following table describes commonly used settings that you can specify in
FindOptions
and FindOneOptions
:
Setting | Description |
---|---|
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: Hint Default: None |
| The projection to use when returning results. Type: Document Default: None |
| 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 |
| 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 |
| 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
Instantiating Options
The Rust driver implements the Builder design pattern for the
creation of many different types, such as FindOneOptions
or
FindOptions
. You can use each type's builder()
method to
construct an options instance by chaining option builder functions
one at a time.
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 shows how to call the find()
method with the
following parameters:
A query filter that matches documents where the value of
unit_price
is less than12.00
and the value ofcategory
is not"kitchen"
A
FindOptions
instance that sorts matched documents byunit_price
in descending order
let opts = FindOptions::builder() .sort(doc! { "unit_price": -1 }) .build(); let mut cursor = my_coll.find( doc! { "$and": vec! [ doc! { "unit_price": doc! { "$lt": 12.00 } }, doc! { "category": doc! { "$ne": "kitchen" } } ] }, opts ).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 shows how to call the find_one()
method with the
following parameters:
A query filter that matches documents where the value of
unit_price
is less than or equal to20.00
A
FindOneOptions
instance that skips the first two matched documents
let opts = FindOneOptions::builder().skip(2).build(); let result = my_coll.find_one( doc! { "unit_price": doc! { "$lte": 20.00 } }, opts ).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 aggregate()
by passing
an AggregateOptions
instance as an optional parameter.
To use default values for each setting, specify the value None
as
the options parameter.
The following table describes commonly used settings that you can specify in
AggregateOptions
:
Setting | Description |
---|---|
| Enables writing to temporary files. If true ,
aggregation stages can write data to the _tmp subdirectory in the
dbPath directory.Type: bool Default: false |
| 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 |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: Collation Default: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: Hint Default: None |
| 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 |
| 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:
A
$group
stage to group documents by thecategory
field and calculate the average of theunit_price
field bycategory
A
$sort
stage to 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, None).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: