Docs Menu
Docs Home
/ / /
Rust Driver
/ / /

Limit the Number of Returned Results

On this page

  • Overview
  • Sample Data for Examples
  • Limit Documents
  • limit() Method Example
  • Options Example
  • Aggregation Example
  • Additional Information
  • API Documentation

In this guide, you can learn how to use the MongoDB Rust Driver to perform limit operations. These operations specify the number of documents returned from a read operation.

Use the limit() method to cap the number of documents that a read operation can return. The operation returns fewer documents if there are not enough documents present to reach the specified limit.

If you use the limit() method with the skip() method, the skip applies first, and the limit only applies to the remaining documents. To learn more about skip operations, see the Skip Returned Results guide.

The examples in this guide use the following Book struct as a model for documents in the books collection:

#[derive(Debug, Serialize, Deserialize)]
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?;

You can specify the maximum number of documents to return in a query or in an aggregation pipeline.

This section describes how to limit results in the following ways:

  • limit() method: Chain the limit() method to the find() method

  • FindOptions struct: Use the limit option

  • Aggregation pipleline: Create a pipeline that uses the $limit stage

To limit the number of documents returned, you can chain the limit() method to the find() method.

This example runs a find() operation that performs the following actions:

  • Sorts the results in ascending order of their length field values

  • Limits the results to the first three documents

let mut cursor = my_coll
.find(doc! {})
.sort(doc! { "length": 1 })
.limit(3).await?;
while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
Book { name: "The Brothers Karamazov", author: "Dostoyevsky", length: 824 }
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }

Alternatively, if you are setting and reusing options for your query, you can use FindOptions. Set the limit field of the FindOptions struct by using the limit() option builder method. Then, chain the with_options() method to the find() method and pass your FindOptions struct as a parameter to the with_options() method.

This example runs a find() operation that performs the following actions:

  • Filters the results to only include documents where the length field is greater than 1000

  • Sorts the results in ascending order of their length field values

  • Limits the results to the first two documents

let filter = doc! { "length": { "$gt": 1000 } };
let find_options = FindOptions::builder()
.sort(doc! { "length": 1 })
.limit(2)
.build();
let mut cursor = my_coll.find(filter).with_options(find_options).await?;
while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }

You can use the $limit stage in an aggregation pipeline to limit returned results. To learn more about aggregation operations, see the Aggregation guide.

This example runs an aggregation pipeline that performs the following actions:

  • Sorts the results in descending order of their length field values

  • Limits the returned results to the first two documents

let pipeline = vec![
doc! { "$match": {} },
doc! { "$sort": { "length": -1 } },
doc! { "$limit": 2 },
];
let mut cursor = my_coll.aggregate(pipeline).await?;
while let Some(result) = cursor.try_next().await? {
println!("{:?}", result);
}
Document({"_id": Int32(3), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)})
Document({"_id": Int32(4), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)})

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

To learn more about any of the methods or types discussed in this guide, see the following API documentation:

Back

Skip Results