-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathfind.txt
543 lines (396 loc) · 15.5 KB
/
find.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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
====
find
====
.. default-domain:: mongodb
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. dbcommand:: find
Executes a query and returns the first batch of results and the
cursor id, from which the client can construct a cursor.
.. |method| replace:: :method:`db.collection.find()` or
:method:`db.collection.findOne()` helper methods
.. include:: /includes/fact-dbcommand-tip
Compatibility
-------------
This command is available in deployments hosted in the following environments:
.. include:: /includes/fact-environments-atlas-only.rst
.. include:: /includes/fact-environments-atlas-support-limited-free.rst
.. include:: /includes/fact-environments-onprem-only.rst
Syntax
------
The :dbcommand:`find` command has the following syntax:
.. versionchanged:: 5.0
.. code-block:: javascript
db.runCommand(
{
find: <string>,
filter: <document>,
sort: <document>,
projection: <document>,
hint: <document or string>,
skip: <int>,
limit: <int>,
batchSize: <int>,
singleBatch: <bool>,
comment: <any>,
maxTimeMS: <int>,
readConcern: <document>,
max: <document>,
min: <document>,
returnKey: <bool>,
showRecordId: <bool>,
tailable: <bool>,
oplogReplay: <bool>,
noCursorTimeout: <bool>,
awaitData: <bool>,
allowPartialResults: <bool>,
collation: <document>,
allowDiskUse : <bool>,
let: <document> // Added in MongoDB 5.0
}
)
.. _find-cmd-fields:
Command Fields
~~~~~~~~~~~~~~
The command accepts the following fields:
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Field
- Type
- Description
* - ``find``
- string
- The name of the collection or :ref:`view <views-landing-page>` to query.
* - ``filter``
- document
- Optional. The query predicate. If unspecified, then all documents in
the collection will match the predicate.
* - .. _find-cmd-sort:
:ref:`sort <find-cmd-sort>`
- document
- Optional. The sort specification for the ordering of the results.
* - ``projection``
- document
- Optional. The :ref:`projection specification <projections>` to
determine which fields to include in the returned documents.
.. include:: /includes/extracts/views-unsupported-projection-operators.rst
* - ``hint``
- string or document
- Optional. Index specification. Specify either the index name as a
string or the index key pattern. If specified, then the query system
will only consider plans using the hinted index.
With the following exception, ``hint`` is required if the command
includes the ``min`` and/or ``max`` fields; ``hint`` is not required
with ``min`` and/or ``max`` if the ``filter`` is an equality condition
on the ``_id`` field ``{ _id: <value> }``.
* - ``skip``
- Positive integer
- Optional. Number of documents to skip. Defaults to 0.
* - ``limit``
- Non-negative integer
- Optional. The maximum number of documents to return. If unspecified,
then defaults to no limit. A limit of 0 is equivalent to setting no
limit.
* - ``batchSize``
- non-negative integer
- Optional. The maximum number of documents within each batch returned in a query result.
By default, the ``find`` command has an initial batch size of ``101`` documents and a maximum
size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller
limit than 16 MiB, but not a larger one. If you set ``batchSize`` to a limit that results
in batches larger than 16 MiB, this option has no effect.
`
A batchSize of 0 means that the cursor will be established, but no documents
will be returned in the first batch.
Unlike the previous wire protocol version, a batchSize of 1 for
the :dbcommand:`find` command does not close the cursor.
* - .. _find-single-batch:
``singleBatch``
- boolean
- Optional. Determines whether to close the cursor after the first
batch. Defaults to false.
* - ``comment``
- any
- .. include:: /includes/extracts/comment-content.rst
.. |comment-include-command| replace:: ``find``
.. include:: /includes/comment-option-getMore-inheritance.rst
* - ``maxTimeMS``
- non-negative integer
- Optional.
.. include:: /includes/maxTimeMS-description.rst
.. include:: /includes/extracts/maxTimeMS-readConcern.rst
* - ``readConcern``
- document
- Optional. Specifies the :term:`read concern`.
.. include:: /includes/fact-readConcern-syntax.rst
.. include:: /includes/fact-readConcern-option-description.rst
The :dbcommand:`getMore` command uses the ``readConcern`` level
specified in the originating ``find`` command.
* - ``max``
- document
- Optional. The *exclusive* upper bound for a specific index. See
:method:`cursor.max()` for details.
To use the ``max`` field, the command must also use ``hint`` unless the
specified ``filter`` is an equality condition on the ``_id`` field
``{ _id: <value> }``.
* - ``min``
- document
- Optional. The *inclusive* lower bound for a specific index. See
:method:`cursor.min()` for details.
To use the ``min`` field, the command must also use ``hint`` unless the
specified ``filter`` is an equality condition on the ``_id`` field
``{ _id: <value> }``.
* - ``returnKey``
- boolean
- Optional. If true, returns only the index keys in the resulting documents.
Default value is false. If returnKey is true and the :dbcommand:`find`
command does not use an index, the returned documents will be empty.
* - ``showRecordId``
- boolean
- Optional. Determines whether to return the record identifier for each document.
If true, adds a field $recordId to the returned documents.
* - ``tailable``
- boolean
- Optional. Returns a :term:`tailable cursor` for a capped collections.
* - ``awaitData``
- boolean
- Optional. Use in conjunction with the tailable option to block a
:dbcommand:`getMore` command on the cursor temporarily at the end
of data rather than returning no data. After a timeout period,
:dbcommand:`find` returns as normal.
* - ``noCursorTimeout``
- boolean
- Optional. Prevents the server from timing out non-session idle cursors
after an inactivity period of 30 minutes. Ignored for cursors that are
part of a session. For more information, refer to
:ref:`Session Idle Timeout <session-idle-timeout>`.
* - :ref:`allowPartialResults <cmd-find-allowPartialResults>`
- boolean
- .. _cmd-find-allowPartialResults:
Optional. For queries against a sharded collection, allows the
command (or subsequent :dbcommand:`getMore` commands) to return
partial results, rather than an error, if one or more queried
shards are unavailable.
.. include:: /includes/find-getmore-partialresults.rst
* - ``collation``
- document
- Optional.
.. include:: /includes/extracts/collation-option.rst
* - .. _find-cmd-allowDiskUse:
:ref:`allowDiskUse <find-cmd-allowDiskUse>`
- boolean
- Optional.
.. include:: /includes/fact-allowDiskUse-option-6.0.rst
``allowDiskUse`` has no effect if MongoDB can satisfy the
specified :ref:`sort <find-cmd-sort>` using an index, *or* if the
blocking sort requires less than 100 megabytes of memory.
For more complete documentation on ``allowDiskUse``,
see :method:`cursor.allowDiskUse()`.
For more information on memory restrictions for large blocking
sorts, see :ref:`sort-index-use`.
* - :ref:`let <find-let-syntax>`
- document
- .. _find-let-syntax:
Optional.
.. include:: /includes/let-variables-syntax.rst
.. include:: /includes/let-variables-syntax-note.rst
For a complete example using ``let`` and variables, see
:ref:`find-let-example`.
.. versionadded:: 5.0
.. _cmd-find-output:
Output
~~~~~~
The command returns a document that contains the cursor information,
including the cursor ID and the first batch of documents. For example,
the following document is returned when run against a sharded
collection:
.. code-block:: javascript
{
"cursor" : {
"firstBatch" : [
{
"_id" : ObjectId("5e8e2ca217b5324fa9847435"),
"zipcode" : "20001",
"x" : 1
},
{
"_id" : ObjectId("5e8e2ca517b5324fa9847436"),
"zipcode" : "30001",
"x" : 1
}
],
"partialResultsReturned" : true,
"id" : NumberLong("668860441858272439"),
"ns" : "test.contacts"
},
"ok" : 1,
"operationTime" : Timestamp(1586380205, 1),
"$clusterTime" : {
"clusterTime" : Timestamp(1586380225, 2),
"signature" : {
"hash" : BinData(0,"aI/jWsUVUSkMw8id+A+AVVTQh9Y="),
"keyId" : NumberLong("6813364731999420435")
}
}
}
.. list-table::
:widths: 20 80
:header-rows: 1
* - Field
- Description
* - ``cursor``
- Contains the cursor information, including the
cursor ``id`` and the ``firstBatch`` of documents.
If the operation against a sharded collection returns partial results
due to the unavailability of the queried shard(s), the ``cursor``
document includes a ``partialResultsReturned`` field. To return partial
results, rather than error, due to the unavailability of the queried
shard(s), the :dbcommand:`find` command must run with
:ref:`allowPartialResults <cmd-find-allowPartialResults>` set to
``true``. See :ref:`allowPartialResults
<cmd-find-allowPartialResults>`.
If the queried shards are initially available for the
:dbcommand:`find` command but one or more shards become
unavailable in subsequent :dbcommand:`getMore` commands, only
the :dbcommand:`getMore` commands run when a queried shard or
shards are unavailable include the ``partialResultsReturned``
flag in the output.
* - ``"ok"``
- Indicates whether the command has succeeded (``1``) or failed
(``0``).
In addition to the aforementioned :dbcommand:`find`-specific fields,
the :method:`db.runCommand()` includes the following information for
replica sets and sharded clusters:
- ``$clusterTime``
- ``operationTime``
See :ref:`db.runCommand() Results <command-response>` for details.
Behavior
--------
``$regex`` Find Queries No Longer Ignore Invalid Regex
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/fact-5.1-regex-find-functionality.rst
Sessions
~~~~~~~~
For cursors created inside a session, you cannot call
:dbcommand:`getMore` outside the session.
Similarly, for cursors created outside of a session, you cannot call
:dbcommand:`getMore` inside a session.
.. _session-idle-timeout:
Session Idle Timeout
````````````````````
.. include:: /includes/extracts/sessions-cursor-timeout.rst
For operations that return a cursor, if the cursor may be idle for
longer than 30 minutes, issue the operation within an explicit session
using :method:`Mongo.startSession()` and periodically refresh the
session using the :dbcommand:`refreshSessions` command. See
:limit:`Session Idle Timeout` for more information.
Transactions
~~~~~~~~~~~~
.. include:: /includes/extracts/transactions-supported-operation.rst
.. include:: /includes/extracts/transactions-operations-getMore.rst
.. include:: /includes/extracts/transactions-usage.rst
.. |operation| replace:: :dbcommand:`find`
Client Disconnection
~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/4.2-changes-disconnect.rst
Stable API
~~~~~~~~~~
When using :ref:`Stable API <stable-api>` V1, the following
:dbcommand:`find` command fields are not supported:
- ``awaitData``
- ``max``
- ``min``
- ``noCursorTimeout``
- ``oplogReplay``
- ``returnKey``
- ``showRecordId``
- ``tailable``
Index Filters and Collations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/index-filters-and-collations.rst
Find Cursor Behavior on Views
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/fact-7.3-singlebatch-cursor.rst
Query Settings
~~~~~~~~~~~~~~
.. include:: /includes/persistent-query-settings-info-for-queries.rst
Examples
--------
Specify a Sort and Limit
~~~~~~~~~~~~~~~~~~~~~~~~
The following command runs the :dbcommand:`find`
command filtering on the ``rating`` field and the ``cuisine`` field.
The command includes a ``projection`` to only return the
following fields in the matching documents: ``_id``, ``name``,
``rating``, and ``address`` fields.
The command sorts the documents in the result set by the ``name``
field and limits the result set to 5 documents.
.. code-block:: javascript
db.runCommand(
{
find: "restaurants",
filter: { rating: { $gte: 9 }, cuisine: "italian" },
projection: { name: 1, rating: 1, address: 1 },
sort: { name: 1 },
limit: 5
}
)
Override Default Read Concern
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To override the default read concern level of :readconcern:`"local"`,
use the ``readConcern`` option.
The following operation on a replica set specifies a :term:`read
concern` of :readconcern:`"majority"` to read the most recent copy of
the data confirmed as having been written to a majority of the nodes.
.. code-block:: javascript
db.runCommand(
{
find: "restaurants",
filter: { rating: { $lt: 5 } },
readConcern: { level: "majority" }
}
)
.. include:: /includes/fact-readConcern-most-recent-data-in-node.rst
The :dbcommand:`getMore` command uses the ``readConcern`` level
specified in the originating :dbcommand:`find` command.
A ``readConcern`` can be specified for the :binary:`~bin.mongosh` method
:method:`db.collection.find()` using the :method:`cursor.readConcern`
method:
.. code-block:: javascript
db.restaurants.find( { rating: { $lt: 5 } } ).readConcern("majority")
For more information on available read concerns, see
:ref:`read-concern`.
Specify Collation
~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/collation-versionadded.rst
The following operation runs the :dbcommand:`find`
command with the collation specified:
.. code-block:: javascript
db.runCommand(
{
find: "myColl",
filter: { category: "cafe", status: "a" },
sort: { category: 1 },
collation: { locale: "fr", strength: 1 }
}
)
:binary:`~bin.mongosh` provides the :method:`cursor.collation()` to
specify :ref:`collation <collation>` for a
:method:`db.collection.find()` operation.
.. _find-let-example:
Use Variables in ``let``
~~~~~~~~~~~~~~~~~~~~~~~~
.. |let-option| replace:: :ref:`let <find-let-syntax>`
.. include:: /includes/let-example-introduction.rst
.. include:: /includes/let-example-find-flavors.rst
.. code-block:: javascript
db.cakeFlavors.runCommand( {
find: db.cakeFlavors.getName(),
filter: { $expr: { $eq: [ "$flavor", "$$targetFlavor" ] } },
let : { targetFlavor: "chocolate" }
} )