-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathlimit.txt
228 lines (166 loc) · 6.26 KB
/
limit.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
.. _golang-limit:
====================================
Limit the Number of Returned Results
====================================
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: read operation, code example, pipeline, customize output
:description: Learn how to limit the number of documents returned in MongoDB read operations using the Go driver, including examples with sorting and aggregation.
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Overview
--------
In this guide, you can learn how to limit the number of documents
returned from a read operation.
Sample Data
~~~~~~~~~~~
The examples in this guide use the following ``Course`` struct as a model for documents
in the ``courses`` collection:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
:start-after: start-course-struct
:end-before: end-course-struct
:language: go
:dedent:
To run the examples in this guide, load the sample data into the
``db.courses`` collection with the following snippet:
.. literalinclude:: /includes/fundamentals/code-snippets/CRUD/limit.go
:language: go
:dedent:
:start-after: begin insertDocs
:end-before: end insertDocs
.. include:: /includes/fundamentals/automatic-db-coll-creation.rst
Each document contains a description of a university course that
includes the course title and maximum enrollment, corresponding to
the ``title`` and ``enrollment`` fields in each document.
Limit
-----
To limit the number of documents returned from a query, pass the
number of documents you want returned to the ``SetLimit()`` method of
the read operation's options.
The following read operations take an options object as a parameter:
- ``Find()``
- ``CountDocuments()``
- ``GridFSBucket.Find()``
If the limit is ``0`` or exceeds the number of matched
documents, the method returns all the documents. If the limit is a
negative number, the method uses the absolute value of the negative
number as the limit and closes the cursor after retrieving
documents.
Example
~~~~~~~
The following example shows how to return two documents that have an
``enrollment`` field value greater than 20:
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{{"enrollment", bson.D{{"$gt", 20}}}}
opts := options.Find().SetLimit(2)
cursor, err := coll.Find(context.TODO(), filter, opts)
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Concepts in Topology","enrollment":35}
{"title":"Ancient Greece","enrollment":100}
Multiple Options
----------------
The driver performs the limit behavior last regardless of the order in which you set
any other options.
Example
~~~~~~~
The following example performs a ``Find()`` operation with the following behavior:
- Sorts the results in descending order on the ``enrollment`` field
- Skips the first document
- Returns the first two of the remaining documents
.. io-code-block::
:copyable: true
.. input::
:language: go
filter := bson.D{}
opts := options.Find().SetSort(bson.D{{"enrollment", -1}}).SetLimit(2).SetSkip(1)
cursor, err := coll.Find(context.TODO(), filter, opts)
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Physiology I","enrollment":60}
{"title":"Concepts in Topology","enrollment":35}
.. tip::
Using any of the following option configurations also produces the same result:
.. code-block:: go
:copyable: false
opts := options.Find().SetSort(bson.D{{"enrollment", -1}}).SetSkip(1).SetLimit(2)
opts := options.Find().SetLimit(2).SetSort(bson.D{{"enrollment", -1}}).SetSkip(1)
opts := options.Find().SetLimit(2).SetSkip(1).SetSort(bson.D{{"enrollment", -1}})
opts := options.Find().SetSkip(1).SetSort(bson.D{{"enrollment", -1}}).SetLimit(2)
opts := options.Find().SetSkip(1).SetLimit(2).SetSort(bson.D{{"enrollment", -1}})
.. _golang-limit-aggregation:
Aggregation
-----------
You can also include the :manual:`$limit </reference/operator/aggregation/limit/>`
stage to specify a limit in an aggregation pipeline.
Example
~~~~~~~
The following example shows how to return three documents:
.. io-code-block::
:copyable: true
.. input::
:language: go
limitStage := bson.D{{"$limit", 3}}
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{limitStage})
if err != nil {
panic(err)
}
var results []Course
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
res, _ := bson.MarshalExtJSON(result, false, false)
fmt.Println(string(res))
}
.. output::
:language: none
:visible: false
{"title":"Romantic Era Music","enrollment":15}
{"title":"Concepts in Topology","enrollment":35}
{"title":"Ancient Greece","enrollment":100}
Additional Information
----------------------
To learn more about the operations mentioned, see the following
guides:
- :ref:`golang-query-document`
- :ref:`golang-retrieve`
- :ref:`golang-sort-results`
- :ref:`golang-skip`
- :ref:`golang-aggregation`
API Documentation
~~~~~~~~~~~~~~~~~
To learn more about any of the methods or types discussed in this
guide, see the following API Documentation:
- `FindOptionsBuilder.SetLimit() <{+api+}/mongo/options#FindOptionsBuilder.SetLimit>`__
- `FindOptionsBuilder.SetSort() <{+api+}/mongo/options#FindOptionsBuilder.SetSort>`__
- `FindOptionsBuilder.SetSkip() <{+api+}/mongo/options#FindOptionsBuilder.SetSkip>`__
- `Aggregate() <{+api+}/mongo#Collection.Aggregate>`__
- `CountDocuments() <{+api+}/mongo#Collection.CountDocuments>`__
- `GridFSBucket.Find() <{+api+}/mongo#GridFSBucket.Find>`__