Skip to content

Commit 22b2b5c

Browse files
committed
DOCSP-43423 Add limit returned results page (#134)
(cherry picked from commit 1704aa5)
1 parent 8ad1179 commit 22b2b5c

File tree

6 files changed

+288
-9
lines changed

6 files changed

+288
-9
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
/fundamentals/crud/read-operations/text-search
1515
/fundamentals/crud/read-operations/sort
1616
/fundamentals/crud/read-operations/skip
17+
/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

@@ -29,11 +30,9 @@ Read Operations
2930
- :ref:`rust-search-text-guide`
3031
- :ref:`rust-sort-guide`
3132
- :ref:`rust-skip-guide`
33+
- :ref:`rust-limit-guide`
3234

3335
.. - :ref:`rust-query-guide`
3436
.. - :ref:`rust-count-guide`
3537
.. - :ref:`rust-distinct-guide`
36-
37-
38-
.. - :ref:`rust-limit-guide`
3938
.. - :ref:`rust-project-guide`
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
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+
This section describes how to limit results in the following ways:
64+
65+
- :ref:`limit() method <rust-limit-method>`: Chain the ``limit()`` method to the
66+
``find()`` method
67+
- :ref:`FindOptions struct <rust-findoptions-limit>`: Use the ``limit`` option
68+
- :ref:`Aggregation pipleline <rust-aggregation-limit>`: Create a pipeline that uses the ``$limit`` stage
69+
70+
.. _rust-limit-method:
71+
72+
limit() Method Example
73+
~~~~~~~~~~~~~~~~~~~~~~~
74+
75+
To limit the number of documents returned, you can chain the ``limit()`` method
76+
to the ``find()`` method.
77+
78+
This example runs a ``find()`` operation that performs the following actions:
79+
80+
- Sorts the results in ascending order of their ``length`` field values
81+
- Limits the results to the first three documents
82+
83+
.. io-code-block::
84+
:copyable: true
85+
86+
.. input:: /includes/fundamentals/code-snippets/crud/limit.rs
87+
:start-after: start-limit-example
88+
:end-before: end-limit-example
89+
:language: rust
90+
:dedent:
91+
92+
.. output::
93+
:language: console
94+
:visible: false
95+
96+
Book { name: "The Brothers Karamazov", author: "Dostoyevsky", length: 824 }
97+
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
98+
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }
99+
100+
.. _rust-findoptions-limit:
101+
102+
Options Example
103+
~~~~~~~~~~~~~~~
104+
105+
Alternatively, if you are setting and reusing options for your query, you can
106+
use ``FindOptions``. Set the ``limit`` field of the ``FindOptions`` struct by
107+
using the ``limit()`` option builder method. Then, chain the ``with_options()``
108+
method to the ``find()`` method and pass your ``FindOptions`` struct as a
109+
parameter to the ``with_options()`` method.
110+
111+
This example runs a ``find()`` operation that performs the following actions:
112+
113+
- Filters the results to only include documents where the ``length`` field is
114+
greater than ``1000``
115+
- Sorts the results in ascending order of their ``length`` field values
116+
- Limits the results to the first two documents
117+
118+
.. io-code-block::
119+
:copyable: true
120+
121+
.. input:: /includes/fundamentals/code-snippets/crud/limit.rs
122+
:start-after: start-limit-options-example
123+
:end-before: end-limit-options-example
124+
:language: rust
125+
:dedent:
126+
127+
.. output::
128+
:language: console
129+
:visible: false
130+
131+
Book { name: "Atlas Shrugged", author: "Rand", length: 1088 }
132+
Book { name: "A Dance with Dragons", author: "Martin", length: 1104 }
133+
134+
.. _rust-aggregation-limit:
135+
136+
Aggregation Example
137+
~~~~~~~~~~~~~~~~~~~
138+
139+
You can use the ``$limit`` stage in an aggregation pipeline to limit returned
140+
results. To learn more about aggregation operations, see the
141+
:ref:`rust-aggregation` guide.
142+
143+
This example runs an aggregation pipeline that performs the following actions:
144+
145+
- Sorts the results in descending order of their ``length`` field values
146+
- Limits the returned results to the first two documents
147+
148+
.. io-code-block::
149+
:copyable: true
150+
151+
.. input:: /includes/fundamentals/code-snippets/crud/limit.rs
152+
:start-after: start-aggregation-limit-example
153+
:end-before: end-aggregation-limit-example
154+
:language: rust
155+
:dedent:
156+
157+
.. output::
158+
:language: console
159+
:visible: false
160+
161+
Document({"_id": Int32(3), "name": String("Les Misérables"), "author": String("Hugo"), "length": Int32(1462)})
162+
Document({"_id": Int32(4), "name": String("A Dance with Dragons"), "author": String("Martin"), "length": Int32(1104)})
163+
164+
Additional Information
165+
----------------------
166+
167+
To learn more about the operations mentioned in this guide, see the following guides:
168+
169+
- :ref:`rust-query-guide`
170+
- :ref:`rust-retrieve-guide`
171+
- :ref:`rust-aggregation`
172+
- :ref:`rust-sort-guide`
173+
174+
API Documentation
175+
~~~~~~~~~~~~~~~~~
176+
177+
To learn more about any of the methods or types discussed in this guide, see the
178+
following API documentation:
179+
180+
- `find() <{+api+}/struct.Collection.html#method.find>`__
181+
- `FindOptions <{+api+}/options/struct.FindOptions.html>`__
182+
- `Cursor <{+api+}/struct.Cursor.html>`__
183+
- `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
@@ -166,7 +166,6 @@ fields that you can set by calling their corresponding builder methods:
166166
| Default: ``None``
167167

168168
.. TODO link to projection fundamentals page under projection setting
169-
.. TODO link to skip fundamentals page under skip setting
170169

171170
.. note:: Setting Options
172171

@@ -390,8 +389,7 @@ following documentation:
390389
- :ref:`rust-aggregation` guide
391390
- :ref:`rust-sort-guide` guide
392391
- :ref:`rust-skip-guide` guide
393-
394-
.. - :ref:`rust-limit-guide`
392+
- :ref:`rust-limit-guide` guide
395393
.. - :ref:`rust-project-guide`
396394
.. - :ref:`rust-collations-guide`
397395

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,6 @@ To learn more about the operations mentioned in this guide, see the following gu
171171
- :ref:`rust-compound-operations`
172172
- :ref:`rust-aggregation`
173173
- :ref:`rust-sort-guide`
174-
.. - :ref:`rust-limit-guide`
175174

176175
API Documentation
177176
~~~~~~~~~~~~~~~~~
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
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+
id: 1,
25+
name: "The Brothers Karamazov".to_string(),
26+
author: "Dostoyevsky".to_string(),
27+
length: 824,
28+
},
29+
Book {
30+
id: 2,
31+
name: "Atlas Shrugged".to_string(),
32+
author: "Rand".to_string(),
33+
length: 1088,
34+
},
35+
Book {
36+
id: 3,
37+
name: "Les Misérables".to_string(),
38+
author: "Hugo".to_string(),
39+
length: 1462,
40+
},
41+
Book {
42+
id: 4,
43+
name: "A Dance with Dragons".to_string(),
44+
author: "Martin".to_string(),
45+
length: 1104,
46+
},
47+
];
48+
49+
my_coll.insert_many(books).await?;
50+
// end-sample-data
51+
52+
// Retrieves documents in the collection, sorts results by their "length" field
53+
// values, and limits the results to three documents.
54+
// start-limit-example
55+
let mut cursor = my_coll
56+
.find(doc! {})
57+
.sort(doc! { "length": 1 })
58+
.limit(3).await?;
59+
60+
while let Some(result) = cursor.try_next().await? {
61+
println!("{:?}", result);
62+
}
63+
// end-limit-example
64+
65+
// Filters the results to only include documents where the "length" field value
66+
// is greater than 1000, then sorts results by their "length" field values, and
67+
// limits the results to the first two documents.
68+
// start-limit-options-example
69+
let filter = doc! { "length": { "$gt": 1000 } };
70+
71+
let find_options = FindOptions::builder()
72+
.sort(doc! { "length": 1 })
73+
.limit(2)
74+
.build();
75+
76+
let mut cursor = my_coll.find(filter).with_options(find_options).await?;
77+
78+
while let Some(result) = cursor.try_next().await? {
79+
println!("{:?}", result);
80+
}
81+
// end-limit-options-example
82+
83+
// Retrieves documents in the collection, sorts results by their "length" field
84+
// values, then limits the results to the first document.
85+
// start-aggregation-limit-example
86+
let pipeline = vec![
87+
doc! { "$match": {} },
88+
doc! { "$sort": { "length": -1 } },
89+
doc! { "$limit": 2 },
90+
];
91+
92+
let mut cursor = my_coll.aggregate(pipeline).await?;
93+
94+
while let Some(result) = cursor.try_next().await? {
95+
println!("{:?}", result);
96+
}
97+
// end-aggregation-limit-example
98+
99+
Ok(())
100+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ async fn main() -> mongodb::error::Result<()> {
8282
// start-aggregation-example
8383
let pipeline = vec![
8484
doc! { "$match": {} },
85-
doc! { "$sort": { "author": 1 } }
85+
doc! { "$sort": { "author": 1 } },
8686
doc! { "$skip": 1 },
8787
];
8888

0 commit comments

Comments
 (0)