Chapter 4. Querying
This chapter looks at querying in detail. The main areas covered are as follows:
You can perform ad hoc queries on the database using the
findorfindOnefunctions and a query document.You can query for ranges, set inclusion, inequalities, and more by using
$-conditionals.Queries return a database cursor, which lazily returns batches of documents as you need them.
There are a lot of metaoperations you can perform on a cursor, including skipping a certain number of results, limiting the number of results returned, and sorting results.
Introduction to find
The find method is used to
perform queries in MongoDB. Querying returns a subset of documents in a
collection, from no documents at all to the entire collection. Which
documents get returned is determined by the first argument to find, which is a document specifying the query
criteria.
An empty query document (i.e., {}) matches everything in the collection. If
find isn’t given a query document, it
defaults to {}. For example, the
following:
>db.c.find()
matches every document in the collection c (and returns these documents in batches).
When we start adding key/value pairs to the query document, we begin
restricting our search. This works in a straightforward way for most
types: numbers match numbers, booleans match booleans, and strings match
strings. Querying for a simple type is as easy as specifying the value
that you are looking for. For example, to find all documents where the
value for "age" is 27, we can add ...