db.collection.find()

Definition

  • db.collection.find(query, projection)

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

Selects documents in a collection or view and returns acursor to the selected documents.

ParameterTypeDescriptionquerydocumentOptional. Specifies selection filter using query operators. To return all documents in a collection, omitthis parameter or pass an empty document ({}).projectiondocumentOptional. Specifies the fields to return in the documents that match thequery filter. To return all fields in the matching documents, omit thisparameter. For details, see Projection.

Returns:A cursor to the documents that match the querycriteria. When the find() method“returns documents,” the method is actually returning a cursor tothe documents.

Behavior

Projection

The projection parameter determines which fields are returned inthe matching documents. The projection parameter takes a documentof the following form:

  1. { field1: <value>, field2: <value> ... }

The <value> can be any of the following:

  • 1 or true to include the field in the return documents.

  • 0 or false to exclude the field.

  • Expression using a Projection Operators.

find() operations on views do not supportthe following projectionoperators:

Note

For the _id field, you do not have to explicitly specify _id:1 to return the _id field. The find() method always returns the _id fieldunless you specify _id: 0 to suppress the field.

A projection cannot contain both include and excludespecifications, except for the exclusion of the id field. Inprojections that _explicitly include fields, the id field is theonly field that you can _explicitly exclude.

Cursor Handling

Executing db.collection.find() in the mongo shellautomatically iterates the cursor to display up to the first 20documents. Type it to continue iteration.

To access the returned documents with a driver, use the appropriatecursor handling mechanism for the driver language.

Read Concern

To specify the read concern fordb.collection.find(), use the cursor.readConcern()method.

Type Bracketing

MongoDB treats some data types as equivalent for comparison purposes.For instance, numeric types undergo conversion before comparison. Formost data types, however,comparison operators onlyperform comparisons on documents where theBSON type of thetarget field matches the type of the query operand. Consider thefollowing collection:

  1. { "_id": "apples", "qty": 5 }
  2. { "_id": "bananas", "qty": 7 }
  3. { "_id": "oranges", "qty": { "in stock": 8, "ordered": 12 } }
  4. { "_id": "avocados", "qty": "fourteen" }

The following query uses $gt to return documents where thevalue of qty is greater than 4.

  1. db.collection.find( { qty: { $gt: 4 } } )

The query returns the following documents:

  1. { "_id": "apples", "qty": 5 }
  2. { "_id": "bananas", "qty": 7 }

The document with _id equal to "avocados" is notreturned because its qty value is of type string while the$gt operand is of type integer.

The document with _id equal to "oranges" is not returnedbecause its qty value is of type object.

Note

To enforce data types in a collection, useSchema Validation.

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

db.collection.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 db.collection.find()disconnects before the operation completes, MongoDB marksthe db.collection.find() for termination (i.e. killOp on theoperation).

Examples

The examples in this section use documents from the bioscollection where the documentsgenerally have the form:

  1. {
  2. "_id" : <value>,
  3. "name" : { "first" : <string>, "last" : <string> }, // embedded document
  4. "birth" : <ISODate>,
  5. "death" : <ISODate>,
  6. "contribs" : [ <string>, ... ], // Array of Strings
  7. "awards" : [
  8. { "award" : <string>, year: <number>, by: <string> } // Array of embedded documents
  9. ...
  10. ]
  11. }

To create and populate the bios collection, seeThe bios Example Collection.

Find All Documents in a Collection

The find() method with no parametersreturns all documents from a collection and returns all fields for thedocuments. For example, the following operation returns all documents inthe bios collection:

  1. db.bios.find()

Find Documents that Match Query Criteria

Query for Equality

  • The following operation returns documents in the bioscollection where _id equals5:
  1. db.bios.find( { _id: 5 } )
  • The following operation returns documents in the bioscollection where the fieldlast in the name embedded document equals "Hopper":
  1. db.bios.find( { "name.last": "Hopper" } )

Note

To access fields in an embedded document, use dot notation ("<embeddeddocument>.<field>").

Query Using Operators

To find documents that match a set of selection criteria, callfind() with the <criteria> parameter.

MongoDB provides various query operators tospecify the criteria.

  • The following operation uses the $in operator to returndocuments in the bios collection where _id equals either5 or ObjectId("507c35dd8fada716c89d0013"):
  1. db.bios.find(
  2. { _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } }
  3. )
  • The following operation uses the $gt operator returns allthe documents from the bios collection where birth isgreater than new Date('1950-01-01'):
  1. db.bios.find( { birth: { $gt: new Date('1950-01-01') } } )
  • The following operation uses the $regex operator to returndocuments in the bios collection where name.last fieldstarts with the letter N (or is "LIKE N%")
  1. db.bios.find(
  2. { "name.last": { $regex: /^N/ } }
  3. )

For a list of the query operators, see Query Selectors.

Query for Ranges

Combine comparison operators to specify ranges for a field. Thefollowing operation returns from the bios collection documents where birth isbetween new Date('1940-01-01') and new Date('1960-01-01')(exclusive):

  1. db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } )

For a list of the query operators, see Query Selectors.

Query for Multiple Conditions

The following operation returns all the documents from the bioscollection where birth fieldis greater than new Date('1950-01-01') and deathfield does not exists:

  1. db.bios.find( {
  2. birth: { $gt: new Date('1920-01-01') },
  3. death: { $exists: false }
  4. } )

For a list of the query operators, see Query Selectors.

Query Embedded Documents

The following examples query the name embedded field in thebios collection.

Query Exact Matches on Embedded Documents

The following operation returns documents in the bios collection where the embedded document name isexactly { first: "Yukihiro", last: "Matsumoto" }, including theorder:

  1. db.bios.find(
  2. { name: { first: "Yukihiro", last: "Matsumoto" } }
  3. )

The name field must match the embedded document exactly. The query doesnot match documents with the following name fields:

  1. {
  2. first: "Yukihiro",
  3. aka: "Matz",
  4. last: "Matsumoto"
  5. }
  6.  
  7. {
  8. last: "Matsumoto",
  9. first: "Yukihiro"
  10. }

Query Fields of an Embedded Document

The following operation returns documents in the bios collection where the embedded document namecontains a field first with the value "Yukihiro" and a fieldlast with the value "Matsumoto". The query uses dotnotation to access fields in an embedded document:

  1. db.bios.find(
  2. {
  3. "name.first": "Yukihiro",
  4. "name.last": "Matsumoto"
  5. }
  6. )

The query matches the document where the name field contains anembedded document with the field first with the value "Yukihiro" and afield last with the value "Matsumoto". For instance, the querywould match documents with name fields that held either of thefollowing values:

  1. {
  2. first: "Yukihiro",
  3. aka: "Matz",
  4. last: "Matsumoto"
  5. }
  6.  
  7. {
  8. last: "Matsumoto",
  9. first: "Yukihiro"
  10. }

For more information and examples, see also Query on Embedded/Nested Documents.

Query Arrays

Query for an Array Element

The following examples query the contribs array in the bioscollection.

  • The following operation returns documents in the bioscollection where the arrayfield contribs contains the element "UNIX":
  1. db.bios.find( { contribs: "UNIX" } )
  • The following operation returns documents in the bioscollection where the arrayfield contribs contains the element "ALGOL" or "Lisp":
  1. db.bios.find( { contribs: { $in: [ "ALGOL", "Lisp" ]} } )
  • The following operation use the $all query operator toreturn documents in the bios collection where the array fieldcontribs contains both the elements "ALGOL" and "Lisp":
  1. db.bios.find( { contribs: { $all: [ "ALGOL", "Lisp" ] } } )

For more examples, see $all. See also $elemMatch.

  • The following operation uses the $size operator to returndocuments in the bios collection where the array sizeof contribs is 4:
  1. db.bios.find( { contribs: { $size: 4 } } )

For more information and examples of querying an array, see:

For a list of array specific query operators, see Array.

Query an Array of Documents

The following examples query the awards array in the bioscollection.

  • The following operation returns documents in the bioscollection where the awardsarray contains an element with award field equals "Turing:
  1. db.bios.find(
  2. { "awards.award": "Turing Award" }
  3. )
  • The following operation returns documents in the bioscollection where the awardsarray contains at least one element with both the award fieldequals "Turing Award" and the year field greater than 1980:
  1. db.bios.find(
  2. { awards: { $elemMatch: { award: "Turing Award", year: { $gt: 1980 } } } }
  3. )

Use the $elemMatch operator to specify multiple criteria onan array element.

For more information and examples of querying an array, see:

For a list of array specific query operators, see Array.

Projections

The projection parameter specifies which fields to return. Theparameter contains either include or exclude specifications, not both,unless the exclude is for the _id field.

Note

Unless the _id field is explicitly excluded in the projectiondocument _id: 0, the _id field is returned.

Specify the Fields to Return

The following operation finds all documents in the bios collection and returns only the namefield, contribs field and _id field:

  1. db.bios.find( { }, { name: 1, contribs: 1 } )

Note

Unless the _id field is explicitly excluded in the projectiondocument _id: 0, the _id field is returned.

Explicitly Excluded Fields

The following operation queries the bios collection and returns all fields _except_the first field in the name embedded document and the birthfield:

  1. db.bios.find(
  2. { contribs: 'OOP' },
  3. { 'name.first': 0, birth: 0 }
  4. )

Explicitly Exclude the _id Field

Note

Unless the _id field is explicitly excluded in the projectiondocument _id: 0, the _id field is returned.

The following operation finds documents in the bios collection and returns only the namefield and the contribs field:

  1. db.bios.find(
  2. { },
  3. { name: 1, contribs: 1, _id: 0 }
  4. )

On Arrays and Embedded Documents

The following operation queries the bios collection and returns the last field inthe name embedded document and the first two elements in the contribsarray:

  1. db.bios.find(
  2. { },
  3. {
  4. _id: 0,
  5. 'name.last': 1,
  6. contribs: { $slice: 2 }
  7. }
  8. )

See also

Project Fields to Return from Query

Iterate the Returned Cursor

The find() method returns acursor to the results.

In the mongo shell, if the returned cursor is not assigned to avariable using the var keyword, the cursor is automatically iterated toaccess up to the first 20 documents that match the query. You can set theDBQuery.shellBatchSize variable to change the number of automaticallyiterated documents.

To manually iterate over the results, assign the returned cursor to a variablewith the var keyword, as shown in the following sections.

With Variable Name

The following example uses the variable myCursor to iterate over thecursor and print the matching documents:

  1. var myCursor = db.bios.find( );
  2.  
  3. myCursor

With next() Method

The following example uses the cursor method next() toaccess the documents:

  1. var myCursor = db.bios.find( );
  2.  
  3. var myDocument = myCursor.hasNext() ? myCursor.next() : null;
  4.  
  5. if (myDocument) {
  6. var myName = myDocument.name;
  7. print (tojson(myName));
  8. }

To print, you can also use the printjson() method instead ofprint(tojson()):

  1. if (myDocument) {
  2. var myName = myDocument.name;
  3. printjson(myName);
  4. }

With forEach() Method

The following example uses the cursor method forEach()to iterate the cursor and access the documents:

  1. var myCursor = db.bios.find( );
  2.  
  3. myCursor.forEach(printjson);

Modify the Cursor Behavior

The mongo shell and the drivers provide several cursor methods that call on thecursor returned by the find() method tomodify its behavior.

Order Documents in the Result Set

The sort() method orders the documents in the resultset. The following operation returns documents in the bioscollection sorted in ascendingorder by the name field:

  1. db.bios.find().sort( { name: 1 } )

sort() corresponds to the ORDER BYstatement in SQL.

Limit the Number of Documents to Return

The limit() method limits the number of documents inthe result set. The following operation returns at most 5 documentsin the bios collection:

  1. db.bios.find().limit( 5 )

limit() corresponds to the LIMITstatement in SQL.

Set the Starting Point of the Result Set

The skip() method controls the starting point of theresults set. The following operation skips the first 5 documents inthe bios collection andreturns all remaining documents:

  1. db.bios.find().skip( 5 )

Specify Collation

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

The collation() method specifies the collation for the db.collection.find() operation.

  1. db.bios.find( { "name.last": "hopper" } ).collation( { locale: "en_US", strength: 1 } )

Combine Cursor Methods

The following statements chain cursor methods limit()and sort():

  1. db.bios.find().sort( { name: 1 } ).limit( 5 )
  2. db.bios.find().limit( 5 ).sort( { name: 1 } )

The two statements are equivalent; i.e. the order in which you chainthe limit() and the sort() methodsis not significant. Both statements return the first five documents, asdetermined by the ascending sort order on ‘name’.