find

Definition

  • find

New in version 3.2.

Executes a query and returns the first batch of results and thecursor id, from which the client can construct a cursor.

Syntax

Changed in version 4.2: MongoDB removes the deprecated maxScan option to thefind command. Use the maxTimeMS option instead.

The find command has the following syntax:

  1. db.runCommand(
  2.  
  3. {
  4. "find": <string>,
  5. "filter": <document>,
  6. "sort": <document>,
  7. "projection": <document>,
  8. "hint": <document or string>,
  9. "skip": <int>,
  10. "limit": <int>,
  11. "batchSize": <int>,
  12. "singleBatch": <bool>,
  13. "comment": <string>,
  14. "maxTimeMS": <int>,
  15. "readConcern": <document>,
  16. "max": <document>,
  17. "min": <document>,
  18. "returnKey": <bool>,
  19. "showRecordId": <bool>,
  20. "tailable": <bool>,
  21. "oplogReplay": <bool>,
  22. "noCursorTimeout": <bool>,
  23. "awaitData": <bool>,
  24. "allowPartialResults": <bool>,
  25. "collation": <document>
  26. }
  27. )

Command Fields

The command accepts the following fields:

FieldTypeDescription
findstringThe name of the collection or view to query.
filterdocumentOptional. The query predicate. If unspecified, then all documents inthe collection will match the predicate.
sortdocumentOptional. The sort specification for the ordering of the results.
projectiondocumentOptional. The projection specification todetermine which fields to include in the returned documents. SeeProject Fields to Return from Query and Projection Operators.find() operations on views do not supportthe following projectionoperators:- $- $elemMatch- $slice- $meta
hintstring or documentOptional. Index specification. Specify either the index name as astring or the index key pattern. If specified, then the query systemwill only consider plans using the hinted index.Changed in version 4.2: With the following exception, hint is required if the commandincludes the min and/or max fields; hint is notrequired with min and/or max if the filter is anequality condition on the id field { _id: <value> }.
skipPositive integerOptional. Number of documents to skip. Defaults to 0.
limitNon-negative integerOptional. The maximum number of documents to return. If unspecified,then defaults to no limit. A limit of 0 is equivalent to setting nolimit.
batchSizenon-negative integerOptional. The number of documents to return in the first batch.Defaults to 101. A batchSize of 0 means that the cursor will beestablished, but no documents will be returned in the first batch.Unlike the previous wire protocol version, a batchSize of 1 forthe find command does not close the cursor.
singleBatchbooleanOptional. Determines whether to close the cursor after the firstbatch. Defaults to false.
commentstringOptional. A comment to attach to the query to help interpret and trace queryprofile data.
maxTimeMSpositive integerOptional. The cumulative time limit in milliseconds for processing operations onthe cursor. MongoDB aborts the operation at the earliest followinginterrupt point.TipWhen specifying linearizable read concern, always use maxTimeMS in case a majority ofdata bearing members are unavailable. maxTimeMS ensures thatthe operation does not block indefinitely and instead ensuresthat the operation returns an error if the readconcern cannot be fulfilled.
readConcerndocumentOptional. Specifies the read concern.Starting in MongoDB 3.6, the readConcern option has the followingsyntax: readConcern: { level: <value> }Possible read concern levels are:- "local". This is the default read concern level forread operations against primary and read operations againstsecondaries when associated with causally consistent sessions.- "available". This is the default for reads againstsecondaries when when not associated with causally consistentsessions. The query returns the instance’s mostrecent data.- "majority". Available for replica sets that useWiredTiger storage engine.- "linearizable". Available for read operations on theprimary only.For more formation on the read concern levels, seeRead Concern Levels.The getMore command uses the readConcern levelspecified in the originating find command.
maxdocumentOptional. The _exclusive upper bound for a specific index. Seecursor.max() for details.Starting in MongoDB 4.2, to use the max field, the command mustalso use hint unless the specified filter is anequality condition on the id field { _id: <value> }.
mindocumentOptional. The _inclusive lower bound for a specific index. Seecursor.min() for details.Starting in MongoDB 4.2, to use the min field, the command mustalso use hint unless the specified filter is anequality condition on the _id field { _id: <value> }.
returnKeybooleanOptional. If true, returns only the index keys in the resulting documents.Default value is false. If returnKey is true and the findcommand does not use an index, the returned documents will be empty.
showRecordIdbooleanOptional. Determines whether to return the record identifier for each document.If true, adds a field $recordId to the returned documents.
tailablebooleanOptional. Returns a tailable cursor for a capped collections.
awaitDatabooleanOptional. Use in conjunction with the tailable option to block agetMore command on the cursor temporarily if at the endof data rather than returning no data. After a timeout period,find returns as normal.
oplogReplaybooleanOptional. An internal command for replaying a replica set’s oplog.To use oplogReplay, the find field must refer to acapped collection and you mustprovide a filter option comparing the ts document field to atimestamp using one of the following comparison operators:- $gte- $gt- $eqFor example, the following command replays documents from the datacapped collection with a timestamplater than or equal to January 1st, 2018 UTC:
  1. { find: "data", oplogReplay: true, filter: { ts: { $gte: new Timestamp(1514764800, 0) } } }
Changed in version 3.6: $eq is now supported.
noCursorTimeoutbooleanOptional. Prevents the server from timing out idle cursors after an inactivityperiod (10 minutes).
allowPartialResultsbooleanOptional. For queries against a sharded collection, returns partial results fromthe mongos if some shards are unavailable instead ofthrowing an error.
collationdocumentOptional.Specifies the collation to use for the operation.Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.The collation option has the following syntax:
  1. collation: { locale: <string>, caseLevel: <boolean>, caseFirst: <string>, strength: <int>, numericOrdering: <boolean>, alternate: <string>, maxVariable: <string>, backwards: <boolean>}
When specifying collation, the locale field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.If the collation is unspecified but the collection has adefault collation (see db.createCollection()), theoperation uses the collation specified for the collection.If no collation is specified for the collection or for theoperations, MongoDB uses the simple binary comparison used in priorversions for string comparisons.You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.New in version 3.4.

Behavior

Sessions

New in version 4.0.

For cursors created inside a session, you cannot callgetMore outside the session.

Similarly, for cursors created outside of a session, you cannot callgetMore inside a session.

Transactions

find can be used inside multi-document transactions.

  • For cursors created outside of a transaction, you cannot callgetMore inside the transaction.
  • For cursors created in a transaction, you cannot callgetMore outside the transaction.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Client Disconnection

Starting in MongoDB 4.2, if the client that issued the finddisconnects before the operation completes, MongoDB marksthe find for termination (i.e. killOp on theoperation).

Examples

Specify a Sort and Limit

The following command runs the findcommand filtering on the rating field and the cuisine field.The command includes a projection to only return thefollowing fields in the matching documents: _id, name,rating, and address fields.

The command sorts the documents in the result set by the namefield and limits the result set to 5 documents.

  1. db.runCommand(
  2. {
  3. find: "restaurants",
  4. filter: { rating: { $gte: 9 }, cuisine: "italian" },
  5. projection: { name: 1, rating: 1, address: 1 },
  6. sort: { name: 1 },
  7. limit: 5
  8. }
  9. )

Override Default Read Concern

To override the default read concern level of "local",use the readConcern option.

The following operation on a replica set specifies a readconcern of "majority" to read the most recent copy ofthe data confirmed as having been written to a majority of the nodes.

To use read concern level of "majority", replicasets must use WiredTiger storage engine.

You can disable read concern "majority" for a deploymentwith a three-member primary-secondary-arbiter (PSA) architecture;however, this has implications for change streams (in MongoDB 4.0 andearlier only) and transactions on sharded clusters. For more information,see Disable Read Concern Majority.

  1. db.runCommand(
  2. {
  3. find: "restaurants",
  4. filter: { rating: { $lt: 5 } },
  5. readConcern: { level: "majority" }
  6. }
  7. )

Regardless of the read concern level, the most recent data on anode may not reflect the most recent version of the data in the system.

The getMore command uses the readConcern levelspecified in the originating find command.

A readConcern can be specified for the mongo shell methoddb.collection.find() using the cursor.readConcernmethod:

  1. db.restaurants.find( { rating: { $lt: 5 } } ).readConcern("majority")

For more information on available read concerns, seeRead Concern.

Specify Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

The following operation runs the findcommand with the collation specified:

  1. db.runCommand(
  2. {
  3. find: "myColl",
  4. filter: { category: "cafe", status: "a" },
  5. sort: { category: 1 },
  6. collation: { locale: "fr", strength: 1 }
  7. }
  8. )

The mongo shell provides the cursor.collation() tospecify collation for adb.collection.find() operation.

See also

Driver Compatibility Changes