- Fast access.
- Ordered results—you don't need to sort data if it's already indexed.
- A smaller working set—you won't need to keep your whole collection in memory if you're only accessing part of it at a given time (read more about correctly sizing your working sets in our previous blog post).
Understanding Whether Your MongoDB Indexes Are Effective
June 9, 2017
Database
One of the variables that can have a major impact on your MongoDB performance is the way you implement indexes. While it's a good idea to use indexes in some form, you need to apply some analysis and tuning to make sure you've set them up to function as effectively as possible.
When you run a query against MongoDB, your server reads from your specified collection and returns documents matching the criteria you've designated. As the query executes, MongoDB will check to see if you've established an index for your documents. If you have, then it will default to using that index to find matches quickly; if you haven't, then it has no choice but to scan your entire collection for matching documents.
You can think about this as analogous to using an index when looking something up in an encyclopedia: if the book has an index and the entries are alphabetical, it's easy for you to find the appropriate page number and the entry you're looking for; if that kind of organization were missing, you'd have to read the entire encyclopedia cover-to-cover to find each appearance of your specified term. Hardly optimal or time-efficient.
One of the central tenets of good MongoDB performance is full collection scans are bad—really bad. They're slow and unfocused, forcing your system to sift through a much larger collection of data than necessary, wasting system time and resources. If your MongoDB instance isn't using an index, then querying a large data set will be prohibitively slow. There are several key advantages to using indexes: