Read¶
Of the four basic database operations (i.e. CRUD), read operations are those that retrieve records or documents from a collection in MongoDB. For general information about read operations and the factors that affect their performance, see Read Operations; for documentation of the other CRUD operations, see the Core MongoDB Operations (CRUD) page.
Overview¶
You can retrieve documents from MongoDB using either of the following methods:
find()¶
The find() method is the primary method to
select documents from a collection. The find()
method returns a cursor that contains a number of documents. Most
drivers provide application developers
with a native iterable interface for handling cursors and accessing
documents. The find() method has the following
syntax:
Corresponding Operation in SQL
The find() method is analogous to
the SELECT statement, while:
- the
<query>argument corresponds to theWHEREstatement, and - the
<projection>argument corresponds to the list of fields to select from the result set.
The examples refer to a collection named
biosthat contains documents with the following prototype:
Return All Documents in a Collection¶
If there is no <query> argument, the :method:`
~db.collection.find()` method selects all documents from a collection.
The following operation returns all documents (or more precisely, a
cursor to all documents) in the bios collection:
Return Documents that Match Query Conditions¶
If there is a <query> argument, the find()
method selects all documents from a collection that satisfies the query
specification.
Equality Matches¶
The following operation returns a cursor to documents in the bios
collection where the field _id equals 5:
Using Operators¶
The following operation returns a cursor to all documents in the
bios collection where the field _id equals 5 or
ObjectId("507c35dd8fada716c89d0013"):
On Arrays¶
Query an Element¶
The following operation returns a cursor to all documents in the
bios collection where the array field contribs contains the
element 'UNIX':
Query Multiple Fields on an Array of Documents¶
The following operation returns a cursor to all documents in the
bios collection where awards array contains a subdocument
element that contains the award field equal to 'Turing Award'
and the year field greater than 1980:
On Subdocuments¶
Exact Matches¶
The following operation returns a cursor to all documents in the
bios collection where the subdocument name is exactly {
first: 'Yukihiro', last: 'Matsumoto' }, including the order:
The name field must match the sub-document exactly, including
order. For instance, the query would not match documents with
name fields that held either of the following values:
Fields of a Subdocument¶
The following operation returns a cursor to all documents in the
bios collection where the subdocument name contains a field
first with the value 'Yukihiro' and a field last with the
value 'Matsumoto'; the query uses dot notation to access
fields in a subdocument:
The query matches the document where the name field contains a
subdocument with the field first with the value 'Yukihiro' and
a field last with the value 'Matsumoto'. For instance, the
query would match documents with name fields that held either of
the following values:
Logical Operators¶
OR Disjunctions¶
The following operation returns a cursor to all documents in the
bios collection where either the field first in the
sub-document name starts with the letter G or where the
field birth is less than new Date('01/01/1945'):
AND Conjunctions¶
The following operation returns a cursor to all documents in the
bios collection where the field first in the subdocument
name starts with the letter K and the array field
contribs contains the element UNIX:
In this query, the parameters (i.e. the selections of both fields)
combine using an implicit logical AND for criteria on different fields
contribs and name.first. For multiple AND criteria on the
same field, use the $and operator.
With a Projection¶
If there is a <projection> argument, the
find() method returns only those fields as
specified in the <projection> argument to include or exclude:
Note
The _id field is implicitly included in the
<projection> argument. In projections that explicitly include
fields, _id is the only field that you can explicitly exclude.
Otherwise, you cannot mix include field and exclude field
specifications.
Specify the Fields to Return¶
The following operation finds all documents in the bios collection
and returns only the name field, the contribs field, and the
_id field:
Explicitly Exclude the _id Field¶
The following operation finds all documents in the bios collection
and returns only the name field and the contribs field:
Return All but the Excluded Fields¶
The following operation finds the documents in the bios collection
where the contribs field contains the element 'OOP' and returns
all fields except the _id field, the first field in the
name subdocument, and the birth field from the matching
documents:
On Arrays and Subdocuments¶
The following operation finds all documents in the bios collection
and returns the the last field in the name subdocument and the
first two elements in the contribs array:
See also
- dot notation for information on “reaching into” embedded sub-documents.
- Arrays for more examples on accessing arrays.
- Subdocuments for more examples on accessing subdocuments.
$elemMatchquery operator for more information on matching array elements.$elemMatchprojection operator for additional information on restricting array elements to return.
Iterate the Returned Cursor¶
The find() method returns a cursor to
the results; however, in the mongo shell, if the returned
cursor is not assigned to a variable, then the cursor is automatically
iterated up to 20 times [1] to print up to the first
20 documents that match the query, as in the following example:
With Variable Name¶
When you assign the find() to a variable, you
can type the name of the cursor variable to iterate up to 20 times
[1] and print the matching documents, as in the
following example:
With next() Method¶
You can use the cursor method next() to
access the documents, as in the following example:
To print, you can also use the printjson() method instead of
print(tojson()):
With forEach() Method¶
You can use the cursor method forEach() to iterate
the cursor and access the documents, as in the following example:
For more information on cursor handling, see:
| [1] | (1, 2) You can use the DBQuery.shellBatchSize to
change the number of iteration from the default value 20. See
Cursor Flags and Cursor Behaviors for more information. |
Modify the Cursor Behavior¶
In addition to the <query> and the <projection> arguments, the
mongo shell and the drivers
provide several cursor methods that you can call on the cursor
returned by find() method to modify
its behavior, such as:
Order Documents in the Result Set¶
The sort() method orders the documents in the
result set.
The following operation returns all documents (or more precisely, a
cursor to all documents) in the bios collection ordered by the
name field ascending:
sort() corresponds to the ORDER BY
statement in SQL.
Limit the Number of Documents to Return¶
The limit() method limits the number of
documents in the result set.
The following operation returns at most 5 documents (or more
precisely, a cursor to at most 5 documents) in the bios collection:
limit() corresponds to the LIMIT
statement in SQL.
Set the Starting Point of the Result Set¶
The skip() method controls the starting point
of the results set.
The following operation returns all documents, skipping the first 5
documents in the bios collection:
Combine Cursor Methods¶
You can chain these cursor methods, as in the following examples [2]:
See the JavaScript cursor methods reference and your driver documentation for additional references. See Cursors for more information regarding cursors.
| [2] | Regardless of the order you chain the
limit() and the sort(), the
request to the server has the structure that treats the
query and the :method:` ~cursor.sort()` modifier as a single object.
Therefore, the limit() operation method is always
applied after the sort() regardless of the
specified order of the operations in the chain. See the meta
query operators for more
information. |
findOne()¶
The findOne() method selects a single
document from a collection and returns that document.
findOne() does not return a cursor.
The findOne() method has the following
syntax:
Except for the return value, findOne() method
is quite similar to the find() method; in
fact, internally, the findOne() method is the
find() method with a limit of 1.
With Empty Query Specification¶
If there is no <query> argument, the
findOne() method selects just one document
from a collection.
The following operation returns a single document from the bios
collection:
With a Query Specification¶
If there is a <query> argument, the
findOne() method selects the first document
from a collection that meets the <query> argument:
The following operation returns the first matching document from the
bios collection where either the field first in the subdocument
name starts with the letter G or where the field birth
is less than new Date('01/01/1945'):
With a Projection¶
You can pass a <projection> argument to
findOne() to control the fields included in
the result set.
Specify the Fields to Return¶
The following operation finds a document in the bios collection and
returns only the name field, the contribs field, and the
_id field:
Return All but the Excluded Fields¶
The following operation returns a document in the bios collection
where the contribs field contains the element OOP and returns
all fields except the _id field, the first field in the
name subdocument, and the birth field from the matching
documents:
Access the findOne Result¶
Although similar to the find() method, because
the findOne() method returns a document rather
than a cursor, you cannot apply the cursor methods such as
limit(), sort(), and
skip() to the result of the
findOne() method. However, you can
access the document directly, as in the example: