If you have worked with a relational database such as MySQL before, indexes should not be new to you. In MongoDB, an index is a special data structure (A B-Tree in computer science terms) that holds information about the values of specific fields of the documents in a collection. When we query the collection on these fields, MongoDB looks into this data structure to quickly sort through and order the documents.
Note
We covered geospatial indexes in the previous chapter. The geospatial index is a special kind of an index (implemented by encoding geohash values on top of B-Tree structures) designed for location-based queries. In this chapter, we will focus on general purpose indexes.
To understand how indexing benefits query performance, consider a collection of movies:
> db.movies.find() { "_id" : ObjectId("4db439153ec7b6fd1c9093ec"), "name" : "Source Code", "genre" : "sci-fi", "year" : 2011 } { "_id" : ObjectId("4db439df3ec7b6fd1c9093ed"), "name...