Sort Results
On this page
Overview
In this guide, you can learn how to use the MongoDB Rust Driver to perform sort operations to specify the order of your read operation results.
Use the sort()
method when building options to change the order in which
read operations return documents. The sort()
method tells MongoDB to order
returned documents by the values of one or more fields in a certain direction.
To sort returned documents by a field in ascending (lowest first) order, use a
value of 1
. To sort in descending (greatest first) order instead, use
-1
. If you do not specify a sort, MongoDB does not guarantee the order of
query results.
Sample Data for Examples
The examples in this guide use the following Book
struct as a model for
documents in the books
collection:
struct Book { name: String, author: String, length: i32, }
The following code shows how to insert sample data into the books
collection:
let uri = "connection string"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Book> = client.database("db").collection("books"); let books = vec![ Book { id: 1, name: "The Brothers Karamazov".to_string(), author: "Dostoyevsky".to_string(), length: 824, }, Book { id: 2, name: "Atlas Shrugged".to_string(), author: "Rand".to_string(), length: 1088, }, Book { id: 3, name: "Les Misérables".to_string(), author: "Hugo".to_string(), length: 1462, }, Book { id: 4, name: "A Dance with Dragons".to_string(), author: "Martin".to_string(), length: 1104, }, ]; my_coll.insert_many(books).await?;
Methods for Sorting
You can sort results retrieved by a query, or you can sort results within an aggregation pipeline.
Chain the sort()
method to the find()
method to sort results retrieved
by the query, as shown in the following example:
let mut cursor = my_coll .find(doc! {}) // 1 for ascending order, -1 for descending order .sort(doc! { "author": 1 }) .await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Options
Alternatively, you can use the sort()
method of the FindOptions
struct.
The following example performs a find()
operation with the following behavior:
Sorts the results in ascending order of the values of the
author
fieldSkips the first document
Returns the remaining documents
let find_options = FindOptions::builder() // 1 for ascending order, -1 for descending order .sort(doc! { "author": 1 }) .skip(1) .build(); let mut cursor = my_coll.find(doc! {}).with_options(find_options).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Aggregation
To sort your results within an aggregation pipeline, create a $sort
stage
and pass the list of stages to the aggregate()
method.
The following example shows how to create a $sort
stage that sorts documents
in ascending order by the values of the author
field:
let pipeline = vec![ doc! { "$match": {} }, // 1 for ascending order, -1 for descending order doc! { "$sort": { "author": 1 } } ]; let mut cursor = my_coll.aggregate(pipeline).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Sorting Direction
The direction of your sort can either be ascending or descending. An ascending sort orders your results from smallest to largest. A descending sort orders your results from largest to smallest.
The following list contains examples of data sorted in ascending order:
Numbers: 1, 2, 3, 43, 43, 55, 120
Dates: 1990-03-10, 1995-01-01, 2005-10-30, 2005-12-21
Words (ASCII): Banana, Dill, carrot, cucumber, hummus
The following list contains examples of data sorted in descending order:
Numbers: 100, 30, 12, 12, 9, 3, 1
Dates: 2020-01-01, 1998-12-11, 1998-12-10, 1975-07-22
Words (reverse ASCII): pear, grapes, apple, Cheese
The following subsections show how to specify these sort criteria.
Ascending
To specify an ascending sort, pass the field you want to sort by and 1
to
the sort()
method.
Example
The following example specifies an ascending sort on the name
field:
let mut cursor = my_coll .find(doc! {}) .sort(doc! { "name": 1 }) .await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Book { "_id": 4, "name": "A Dance with Dragons", "author": Martin, "length": 1104 } Book { "_id": 2, "name": "Atlas Shrugged", "author": Rand, "length": 1088 } Book { "_id": 3, "name": "Les Miserables", "author": Hugo, "length": 1462 } Book { "_id": 1, "name": "The Brothers Karamazov", "author": Dostoevsky, "length": 824 }
Descending
To specify a descending sort, pass the field you want to sort by and -1
to
the sort()
method.
Example
The following example specifies a descending sort on the name
field:
let mut cursor = my_coll .find(doc! {}) .sort(doc! { "name": -1 }) .await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); }
Book { "_id": 1, "name": "The Brothers Karamazov", "author": Dostoevsky, "length": 824 } Book { "_id": 3, "name": "Les Miserables", "author": Hugo, "length": 1462 } Book { "_id": 2, "name": "Atlas Shrugged", "author": Rand, "length": 1088 } Book { "_id": 4, "name": "A Dance with Dragons", "author": Martin, "length": 1104 }
Additional Information
To learn more about the operations mentioned in this guide, see the following:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: