Skip to Content
MongoDB: The Definitive Guide, 2nd Edition
book

MongoDB: The Definitive Guide, 2nd Edition

by Kristina Chodorow
May 2013
Intermediate to advanced content levelIntermediate to advanced
430 pages
11h 2m
English
O'Reilly Media, Inc.
Content preview from MongoDB: The Definitive Guide, 2nd Edition

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 find or findOne functions 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 ...

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.
Start your free trial

You might also like

MongoDB: The Definitive Guide, 3rd Edition

MongoDB: The Definitive Guide, 3rd Edition

Shannon Bradshaw, Eoin Brazil, Kristina Chodorow
MongoDB: The Definitive Guide

MongoDB: The Definitive Guide

Kristina Chodorow, Michael Dirolf

Publisher Resources

ISBN: 9781449344795Errata Page