Chapter 5. Indexing

Indexes are the way to make queries go vroom. Database indexes are similar to a book’s index: instead of looking through the whole book, the database takes a shortcut and just looks in the index, allowing it to do queries orders of magnitude faster. Once it finds the entry in the index, it can jump right to the location of the desired document.

Extending this metaphor to the breaking point, creating database indexes is like deciding how a book’s index will be organized. You have the advantage of knowing what kinds of queries you’ll be doing and thus what types of information the database will need to find quickly. If all of your queries involve the "date" key, for example, you probably need an index on "date" (at least). If you will be querying for usernames, you don’t need to index the "user_num" key, because you aren’t querying on it.

Introduction to Indexing

It can be tricky to figure out what the optimal index for your queries is, but it is well worth the effort. Queries that otherwise take minutes can be instantaneous with the proper indexes.

Tip

MongoDB’s indexes work almost identically to typical relational database indexes, so if you are familiar with those, you can skim this section for syntax specifics. We’ll go over some indexing basics, but keep in mind that it’s an extensive topic and most of the material out there on index optimization for MySQL/Oracle/SQLite will apply equally well to MongoDB.

Suppose that you are querying for a single key, such as the ...

Get MongoDB: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.