@@ -23,6 +23,311 @@ Overview
23
23
In this guide, you can learn how to specify which documents to return from a read
24
24
operation by using the following methods:
25
25
26
- - ``limit``: Specifies the maximum number of documents to return from a query.
27
- - ``sort``: Specifies the sort order for the returned documents.
28
- - ``skip``: Specifies the number of documents to skip before returning query results.
26
+ - ``sort()``: Specifies the sort order for the returned documents.
27
+ - ``limit()``: Specifies the maximum number of documents to return from a query.
28
+ - ``skip()``: Specifies the number of documents to skip before returning query results.
29
+
30
+ You can use these methods either by chaining them to your read operation or by specifying them in an
31
+ ``options`` object in your call to your read operation.
32
+
33
+ .. note::
34
+
35
+ If you chain ``sort()``, ``limit()``, or ``skip()`` to a read operation, you must
36
+ specify all methods before iterating the cursor. If you specify a method after
37
+ iterating the cursor, the method you specified does not apply to the operation.
38
+
39
+ Sample Data for Examples
40
+ ~~~~~~~~~~~~~~~~~~~~~~~~
41
+
42
+ To run the examples in this guide, use the following code snippet to insert documents
43
+ that describe books into the ``myDB.books`` collection:
44
+
45
+ .. code-block:: javascript
46
+
47
+ const myDB = client.db("myDB");
48
+ const myColl = myDB.collection("books");
49
+
50
+ await myColl.insertMany([
51
+ { "_id": 1, "name": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 },
52
+ { "_id": 2, "name": "Les Misérables", "author": "Hugo", "length": 1462 },
53
+ { "_id": 3, "name": "Atlas Shrugged", "author": "Rand", "length": 1088 },
54
+ { "_id": 4, "name": "Infinite Jest", "author": "Wallace", "length": 1104 },
55
+ { "_id": 5, "name": "Cryptonomicon", "author": "Stephenson", "length": 918 },
56
+ { "_id": 6, "name": "A Dance With Dragons", "author": "Martin", "length": 1104 },
57
+ ]);
58
+
59
+ .. include:: /includes/access-cursor-note.rst
60
+
61
+ .. _node-fundamentals-sort:
62
+
63
+ Sort
64
+ ----
65
+
66
+ Use the ``sort()`` method to change the order in which read operations return
67
+ documents. This method tells MongoDB to order returned documents by the
68
+ values of one or more fields in a certain direction. To sort returned
69
+ documents by a field in ascending (lowest first) order, use a value of
70
+ ``1``. To sort in descending (greatest first) order instead, use ``-1``.
71
+ If you do not specify a sort, MongoDB does not guarantee the order of
72
+ query results.
73
+
74
+ The following example passes the sort document to a read operation to ensure that the
75
+ operation returns books with longer lengths before books with shorter
76
+ lengths:
77
+
78
+ .. code-block:: javascript
79
+ :emphasize-lines: 4
80
+
81
+ // define an empty query document
82
+ const query = {};
83
+ // sort in descending (-1) order by length
84
+ const sort = { length: -1 };
85
+ const cursor = myColl.find(query).sort(sort);
86
+ for await (const doc of cursor) {
87
+ console.dir(doc);
88
+ }
89
+
90
+ In this case, the number ``-1`` tells the read operation to sort the
91
+ books in descending order by length. ``find()`` returns the following
92
+ documents when this sort is used with an empty query:
93
+
94
+ .. code-block:: json
95
+ :copyable: false
96
+
97
+ { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }
98
+ { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
99
+ { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 }
100
+ { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 }
101
+ { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
102
+ { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }
103
+
104
+ Sometimes, the order of two or more documents is ambiguous using a specified sort. In the
105
+ preceding example, the documents that have ``title`` values of ``"A Dance with Dragons"`` and
106
+ ``"Infinite Jest"`` both have a ``length`` of ``1104``, so the order in which they are
107
+ returned is not guaranteed. To resolve ties in your sorted results in a repeatable way,
108
+ add more fields to the sort document:
109
+
110
+ .. code-block:: javascript
111
+ :emphasize-lines: 4
112
+
113
+ // define an empty query document
114
+ const query = {};
115
+ // sort in ascending (1) order by length
116
+ const sort = { length: 1, author: 1 };
117
+ const cursor = myColl.find(query).sort(sort);
118
+ for await (const doc of cursor) {
119
+ console.dir(doc);
120
+ }
121
+
122
+ With the addition of the ``author`` field to the sort document, the read operation sorts
123
+ matching documents first by ``length`` then, if there is a tie, by ``author``. Matched
124
+ document fields are compared in the same order as fields are specified in the sort
125
+ document. ``find()`` returns the following ordering of documents when this sort is used on
126
+ the documents matching the query:
127
+
128
+ .. code-block:: json
129
+ :copyable: false
130
+
131
+ { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }
132
+ { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
133
+ { "_id": 3, "title": "Atlas Shrugged", "author": "Rand", "length": 1088 }
134
+ { "_id": 6, "title": "A Dance with Dragons", "author": "Martin", "length": 1104 }
135
+ { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
136
+ { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }
137
+
138
+ .. _node-fundamentals-limit:
139
+
140
+ Limit
141
+ -----
142
+
143
+ Use the ``limit()`` method to cap the number of documents that can be returned from a read
144
+ operation. This method specifies the maximum number of documents that the operation can
145
+ return, but the operation can return a smaller number of documents if there are not enough
146
+ documents present to reach the limit. If ``limit()`` is used with the :ref:`skip()
147
+ <node-fundamentals-skip>` method, the skip applies first and the limit only applies to the
148
+ documents left over after the skip.
149
+
150
+ This example performs the following actions:
151
+
152
+ - Uses an empty query filter to match all documents in the collection
153
+ - Calls the ``sort()`` method to apply a descending sort on the ``length`` field to the results
154
+ - Calls the ``limit()`` method to return only the first ``3`` results
155
+
156
+ .. code-block:: javascript
157
+ :emphasize-lines: 5
158
+
159
+ // define an empty query document
160
+ const query = {};
161
+ // sort in descending (-1) order by length
162
+ const sort = { length: -1 };
163
+ const limit = 3;
164
+ const cursor = myColl.find(query).sort(sort).limit(limit);
165
+ for await (const doc of cursor) {
166
+ console.dir(doc);
167
+ }
168
+
169
+ The code example above outputs the following three documents, sorted by
170
+ length:
171
+
172
+ .. code-block:: json
173
+ :copyable: false
174
+
175
+ { "_id": 2, "title": "Les Misérables", "author": "Hugo", "length": 1462 }
176
+ { "_id": 6, "title": "A Dance With Dragons", "author": "Martin", "length": 1104 }
177
+ { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
178
+
179
+ .. note::
180
+
181
+ The order in which you call ``limit()`` and ``sort()`` does not matter because the
182
+ driver reorders the calls to apply the sort first. The following two calls are
183
+ equivalent:
184
+
185
+ .. code-block:: javascript
186
+
187
+ myColl.find(query).sort({ length: -1 }).limit(3);
188
+ myColl.find(query).limit(3).sort({ length: -1 });
189
+
190
+ You can also apply ``sort()`` and ``limit()`` by specifying them in an
191
+ ``options`` object in your call to the ``find()`` method. The following two
192
+ calls are equivalent:
193
+
194
+ .. code-block:: javascript
195
+
196
+ myColl.find(query).sort({ length: -1 }).limit(3);
197
+ myColl.find(query, { sort: { length: -1 }, limit: 3 });
198
+
199
+ For more information on the ``options`` settings for the ``find()``
200
+ method, see the
201
+ `API documentation on find() <{+api+}/classes/Collection.html#find>`__.
202
+
203
+ .. _node-fundamentals-skip:
204
+
205
+ Skip
206
+ ----
207
+
208
+ Use the ``skip()`` method to omit documents from the beginning of the read operation
209
+ results. You can combine ``skip()`` with
210
+ :ref:`sort() <node-fundamentals-sort>` to omit the top
211
+ (for descending order) or bottom (for ascending order) results for a
212
+ given query. Since the :manual:`order of documents returned
213
+ </reference/method/cursor.sort/#result-ordering>` is not guaranteed in
214
+ the absence of a sort, using ``skip()`` without using ``sort()`` omits
215
+ arbitrary documents.
216
+
217
+ If the value of ``skip()`` exceeds the number of matched documents for
218
+ a query, then that query returns no documents.
219
+
220
+ This example queries the collection for the books with the fifth and sixth highest lengths
221
+ by performing the following actions:
222
+
223
+ - Uses an empty query filter to match all documents in the collection
224
+ - Calls the ``sort()`` method to apply a descending sort to the ``length`` field, which returns longer books before shorter books
225
+ - Calls the ``skip()`` method to omit the first four matching documents from the result
226
+
227
+ .. code-block:: javascript
228
+
229
+ // define an empty query document
230
+ const query = {};
231
+ const sort = { length: -1 };
232
+ const skip = 4;
233
+ const cursor = myColl.find(query).sort(sort).skip(skip);
234
+ for await (const doc of cursor) {
235
+ console.dir(doc);
236
+ }
237
+
238
+ Since the query skips the first four matching documents, the preceding code snippet prints
239
+ the fifth and sixth highest length documents:
240
+
241
+ .. code-block:: json
242
+ :copyable: false
243
+
244
+ { "_id": 5, "title": "Cryptonomicon", "author": "Stephenson", "length": 918 }
245
+ { "_id": 1, "title": "The Brothers Karamazov", "author": "Dostoyevsky", "length": 824 }
246
+
247
+ You can also apply ``skip()`` and ``sort()`` by specifying them in an
248
+ ``options`` object in your call to the ``find()`` method. The following two
249
+ calls are equivalent:
250
+
251
+ .. code-block:: javascript
252
+
253
+ myColl.find(query).sort({ length: -1 }).skip(4);
254
+ myColl.find(query, { sort: { length: -1 }, skip: 4});
255
+
256
+ For more information on the ``options`` settings for the ``find()``
257
+ method, see the
258
+ `API documentation on find() <{+api+}/classes/Collection.html#find>`__.
259
+
260
+ .. _node-fundamentals-combine-lim-sort-skip:
261
+
262
+ Combine Limit, Sort, and Skip
263
+ -----------------------------
264
+
265
+ You can combine the ``limit``, ``sort``, and ``skip`` options in a single
266
+ operation. This allows you to set a maximum number of sorted documents to
267
+ return, skipping a specified number of documents before returning.
268
+
269
+ The following example returns documents with the ``length`` value of
270
+ ``"1104"``. The results are sorted in alphabetical order, skipping the first
271
+ document and includes only the first result:
272
+
273
+ .. code-block:: javascript
274
+
275
+ // define a query to look for length value of 1104
276
+ const query = {length: "1104"};
277
+ const options = {
278
+ // sort in alphabetical (1) order by title
279
+ sort : { title: 1 },
280
+ // omit the first document
281
+ skip : 1,
282
+ // returns only the first result
283
+ limit: 1,
284
+ }
285
+ const cursor = myColl.find(query, options);
286
+ for await (const doc of cursor) {
287
+ console.dir(doc);
288
+ }
289
+
290
+ .. code-block:: json
291
+ :copyable: false
292
+
293
+ { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
294
+
295
+ .. note::
296
+
297
+ The order in which you call these methods doesn't change the documents
298
+ that are returned. The driver automatically reorders the calls to perform the
299
+ sort and skip operations first, and the limit operation afterward.
300
+
301
+ You can also limit, sort, and skip results by chaining each method to the ``find`` method.
302
+ The following example specifies the same query as the preceding example:
303
+
304
+ .. io-code-block::
305
+
306
+ .. input::
307
+ :language: javascript
308
+
309
+ myColl.find(query).sort({ title: 1 }).skip(1).limit(1);
310
+
311
+ .. output::
312
+ :language: json
313
+ :visible: false
314
+
315
+ { "_id": 4, "title": "Infinite Jest", "author": "Wallace", "length": 1104 }
316
+
317
+ Additional Information
318
+ ----------------------
319
+
320
+ For more information about specifying a query, see :ref:`node-query`.
321
+
322
+ For more information about retrieving documents, see :ref:`node-fundamentals-retrieve-data`.
323
+
324
+ API Documentation
325
+ ~~~~~~~~~~~~~~~~~
326
+
327
+ To learn more about any of the methods discussed in this
328
+ guide, see the following API documentation:
329
+
330
+ - `find() <{+api+}/classes/Collection.html#find>`__
331
+ - `limit() <{+api+}/classes/FindCursor.html#limit>`__
332
+ - `sort() <{+api+}/classes/FindCursor.html#sort>`__
333
+ - `skip() <{+api+}/classes/FindCursor.html#skip>`__
0 commit comments