/
cursor.limit.txt
88 lines (59 loc) · 2.51 KB
/
cursor.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
==============
cursor.limit()
==============
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. method:: cursor.limit()
.. include:: /includes/fact-mongosh-shell-method.rst
Use the :method:`~cursor.limit()` method on a cursor to specify the maximum
number of documents the cursor will return. :method:`~cursor.limit()` is
analogous to the ``LIMIT`` statement in a SQL database.
.. note::
You must apply :method:`~cursor.limit()` to the cursor before
retrieving any documents from the database.
Use :method:`~cursor.limit()` to maximize performance and prevent
MongoDB from returning more results than required for processing.
The :method:`~cursor.limit()` method has the following prototype form:
.. code-block:: javascript
db.collection.find(<query>).limit(<number>)
Behavior
--------
Supported Values
~~~~~~~~~~~~~~~~
The behavior of :method:`~cursor.limit()` is undefined for values less
than -2\ :sup:`31` and greater than 2\ :sup:`31`.
You must specify a numeric value for :method:`~cursor.limit()`.
Zero Value
~~~~~~~~~~
A :method:`~cursor.limit()` value of 0 (i.e. :method:`.limit(0)
<cursor.limit()>`) is equivalent to setting no limit.
Negative Values
~~~~~~~~~~~~~~~
A negative limit is similar to a positive limit but closes the cursor
after returning a single :ref:`batch <cursor-batches>` of results. As
such, with a negative limit, if the limited result set does not fit
into a single batch, the number of documents received will be less than
the specified limit. By passing a negative limit, the client indicates
to the server that it will not ask for a subsequent batch via
``getMore``.
Using ``limit()`` with ``sort()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If using :method:`~cursor.limit()` with :method:`~cursor.sort()`, be
sure to include at least one field in your sort that contains
unique values, before passing results to :method:`~cursor.limit()`.
Sorting on fields that contain duplicate values may return an
inconsistent sort order for those duplicate fields over multiple
executions, especially when the collection is actively receiving writes.
The easiest way to guarantee sort consistency is to include the
``_id`` field in your sort query.
See :ref:`Consistent sorting with the sort() method
<sort-cursor-consistent-sorting>` for more information.
Using ``limit()`` with ``skip()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: includes/reference/skip-limit.rst