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.Some queries cannot be expressed as query documents, even using $ conditionals. For these types of complex queries, you can use a
$whereclause to harness the full expressive power of JavaScript.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 to be performed.
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()
returns everything in the collection c.
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. Integers match integers, booleans match booleans, and strings match strings. Querying ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access