Skip to content

Commit 2c7810f

Browse files
committed
DOCSP-45853 Backport Limit Results (#168)
(cherry picked from commit 56d9808)
1 parent 6ff40e5 commit 2c7810f

File tree

6 files changed

+234
-10
lines changed

6 files changed

+234
-10
lines changed

source/fundamentals/crud/read-operations.txt

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,12 @@ Read Operations
1414
Search Text </fundamentals/crud/read-operations/text-search>
1515
Sort Data </fundamentals/crud/read-operations/sort>
1616
Skip Results </fundamentals/crud/read-operations/skip>
17+
Limit Results </fundamentals/crud/read-operations/limit>
1718

1819
..
1920
/fundamentals/crud/read-operations/count
2021
/fundamentals/crud/read-operations/distinct
21-
/fundamentals/crud/read-operations/limit
22+
2223
/fundamentals/crud/read-operations/project
2324

2425
- :ref:`rust-query-guide`
@@ -28,11 +29,9 @@ Read Operations
2829
- :ref:`rust-search-text-guide`
2930
- :ref:`rust-sort-guide`
3031
- :ref:`rust-skip-guide`
32+
- :ref:`rust-limit-guide`
3133

3234
.. - :ref:`rust-query-guide`
3335
.. - :ref:`rust-count-guide`
3436
.. - :ref:`rust-distinct-guide`
35-
36-
37-
.. - :ref:`rust-limit-guide`
3837
.. - :ref:`rust-project-guide`
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
.. _rust-limit-guide:
2+
3+
====================================
4+
Limit the Number of Returned Results
5+
====================================
6+
7+
.. facet::
8+
:name: genre
9+
:values: reference
10+
11+
.. meta::
12+
:keywords: read operation, code example, pipeline, customize output
13+
14+
.. contents:: On this page
15+
:local:
16+
:backlinks: none
17+
:depth: 2
18+
:class: singlecol
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use the {+driver-long+} to perform **limit**
24+
operations. These operations specify the number of documents returned from a
25+
read operation.
26+
27+
Use the ``limit()`` method to cap the number of documents that a read operation
28+
can return. The operation returns fewer documents if there are not enough
29+
documents present to reach the specified limit.
30+
31+
If you use the ``limit()`` method with the ``skip()`` method, the skip applies
32+
first, and the limit only applies to the remaining documents. To learn more
33+
about skip operations, see the :ref:`Skip Returned Results <rust-skip-guide>`
34+
guide.
35+
36+
Sample Data for Examples
37+
------------------------
38+
39+
The examples in this guide use the following ``Book`` struct as a model for
40+
documents in the ``books`` collection:
41+
42+
.. literalinclude:: /includes/fundamentals/code-snippets/crud/limit.rs
43+
:start-after: start-book-struct
44+
:end-before: end-book-struct
45+
:language: rust
46+
:dedent:
47+
48+
The following code shows how to insert sample data into the ``books``
49+
collection:
50+
51+
.. literalinclude:: /includes/fundamentals/code-snippets/crud/limit.rs
52+
:start-after: start-sample-data
53+
:end-before: end-sample-data
54+
:language: rust
55+
:dedent:
56+
57+
Limit Documents
58+
---------------
59+
60+
You can specify the maximum number of documents to return in a query or in an
61+
aggregation pipeline.
62+
63+
.. _rust-limit-method:
64+
65+
Query Results Example
66+
~~~~~~~~~~~~~~~~~~~~~
67+
68+
To limit the number of documents returned, you can initialize a ``FindOptions``
69+
instance and specify the number of documents you want to limit using the
70+
``limit()`` method. Then, pass your ``FindOptions`` struct as a parameter to the
71+
``find()`` method.
72+
73+
This example runs a ``find()`` operation that performs the following actions:
74+
75+
- Filters the results to only include documents where the ``length`` field is
76+
greater than ``1000``
77+
- Sorts the results in ascending order of their ``length`` field values
78+
- Limits the results to the first two documents
79+
80+
.. io-code-block::
81+
:copyable: true
82+
83+
.. input:: /includes/fundamentals/code-snippets/crud/limit.rs
84+
:start-after: start-limit-example
85+
:end-before: end-limit-example
86+
:language: rust
87+
:dedent:
88+
89+
.. output::
90+
:language: console
91+
:visible: false
92+
93+
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
94+
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }
95+
96+
.. _rust-aggregation-limit:
97+
98+
Aggregation Example
99+
~~~~~~~~~~~~~~~~~~~
100+
101+
You can use the ``$limit`` stage in an aggregation pipeline to limit returned
102+
results. To learn more about aggregation operations, see the
103+
:ref:`rust-aggregation` guide.
104+
105+
This example runs an aggregation pipeline that performs the following actions:
106+
107+
- Sorts the results in descending order of their ``length`` field values
108+
- Limits the returned results to the first two documents
109+
110+
.. io-code-block::
111+
:copyable: true
112+
113+
.. input:: /includes/fundamentals/code-snippets/crud/limit.rs
114+
:start-after: start-aggregation-limit-example
115+
:end-before: end-aggregation-limit-example
116+
:language: rust
117+
:dedent:
118+
119+
.. output::
120+
:language: console
121+
:visible: false
122+
123+
Document({"_id": ObjectId("..."), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)})
124+
Document({"_id": ObjectId("..."), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)})
125+
126+
Additional Information
127+
----------------------
128+
129+
To learn more about the operations mentioned in this guide, see the following guides:
130+
131+
- :ref:`rust-query-guide`
132+
- :ref:`rust-retrieve-guide`
133+
- :ref:`rust-aggregation`
134+
- :ref:`rust-sort-guide`
135+
136+
API Documentation
137+
~~~~~~~~~~~~~~~~~
138+
139+
To learn more about any of the methods or types discussed in this guide, see the
140+
following API documentation:
141+
142+
- `find() <{+api+}/struct.Collection.html#method.find>`__
143+
- `FindOptions <{+api+}/options/struct.FindOptions.html>`__
144+
- `Cursor <{+api+}/struct.Cursor.html>`__
145+
- `aggregate() <{+api+}/struct.Collection.html#method.aggregate>`__

source/fundamentals/crud/read-operations/retrieve.txt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,6 @@ The following table describes commonly used settings that you can specify in
169169
| Default: ``None``
170170

171171
.. TODO link to projection fundamentals page under projection setting
172-
.. TODO link to skip fundamentals page under skip setting
173172

174173
.. note:: Instantiating Options
175174

@@ -396,8 +395,7 @@ following documentation:
396395
- :ref:`rust-aggregation` guide
397396
- :ref:`rust-sort-guide` guide
398397
- :ref:`rust-skip-guide` guide
399-
400-
.. - :ref:`rust-limit-guide`
398+
- :ref:`rust-limit-guide` guide
401399
.. - :ref:`rust-project-guide`
402400
.. - :ref:`rust-collations-guide`
403401

source/fundamentals/crud/read-operations/skip.txt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,8 +130,7 @@ To learn more about the operations mentioned in this guide, see the following gu
130130
- :ref:`rust-compound-operations`
131131
- :ref:`rust-aggregation`
132132
- :ref:`rust-sort-guide`
133-
134-
.. - :ref:`rust-limit-guide`
133+
- :ref:`rust-limit-guide`
135134

136135
API Documentation
137136
~~~~~~~~~~~~~~~~~
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
use std::env;
2+
use mongodb::{ bson::doc, bson::Document, Client, Collection, options::FindOptions };
3+
use serde::{Deserialize, Serialize};
4+
use futures::stream::TryStreamExt;
5+
6+
// start-book-struct
7+
#[derive(Debug, Serialize, Deserialize)]
8+
struct Book {
9+
name: String,
10+
author: String,
11+
length: i32,
12+
}
13+
// end-book-struct
14+
15+
#[tokio::main]
16+
async fn main() -> mongodb::error::Result<()> {
17+
// start-sample-data
18+
let uri = "connection string";
19+
let client = Client::with_uri_str(uri).await?;
20+
let my_coll: Collection<Book> = client.database("db").collection("books");
21+
22+
let books = vec![
23+
Book {
24+
name: "The Brothers Karamazov".to_string(),
25+
author: "Dostoyevsky".to_string(),
26+
length: 824,
27+
},
28+
Book {
29+
name: "Atlas Shrugged".to_string(),
30+
author: "Rand".to_string(),
31+
length: 1088,
32+
},
33+
Book {
34+
name: "Les Misérables".to_string(),
35+
author: "Hugo".to_string(),
36+
length: 1462,
37+
},
38+
Book {
39+
name: "A Dance with Dragons".to_string(),
40+
author: "Martin".to_string(),
41+
length: 1104,
42+
},
43+
];
44+
45+
my_coll.insert_many(books, None).await?;
46+
// end-sample-data
47+
48+
// Filters the results to only include documents where the "length" field value
49+
// is greater than 1000, then sorts results by their "length" field values, and
50+
// limits the results to the first two documents.
51+
// start-limit-example
52+
let filter = doc! { "length": { "$gt": 1000 } };
53+
54+
let find_options = FindOptions::builder()
55+
.sort(doc! { "length": 1 })
56+
.limit(2)
57+
.build();
58+
59+
let mut cursor = my_coll.find(filter, find_options).await?;
60+
61+
while let Some(result) = cursor.try_next().await? {
62+
println!("{:?}", result);
63+
}
64+
// end-limit-example
65+
66+
// Retrieves documents in the collection, sorts results by their "length" field
67+
// values, then limits the results to the first document.
68+
// start-aggregation-limit-example
69+
let pipeline = vec![
70+
doc! { "$match": {} },
71+
doc! { "$sort": { "length": -1 } },
72+
doc! { "$limit": 2 },
73+
];
74+
75+
let mut cursor = my_coll.aggregate(pipeline, None).await?;
76+
77+
while let Some(result) = cursor.try_next().await? {
78+
println!("{:?}", result);
79+
}
80+
// end-aggregation-limit-example
81+
82+
Ok(())
83+
}

source/includes/fundamentals/code-snippets/crud/skip.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ async fn main() -> mongodb::error::Result<()> {
6464
// start-aggregation-example
6565
let pipeline = vec![
6666
doc! { "$match": {} },
67-
doc! { "$sort": { "author": 1 } }
67+
doc! { "$sort": { "author": 1 } },
6868
doc! { "$skip": 1 },
6969
];
7070

0 commit comments

Comments
 (0)