Lesson 1: How Indexes Work / Learn

Video Transcript (English)

One of the best tools for optimizing queries for MongoDB are indexes, especially compound indexes. In this video, you’ll learn how index values are stored and how indexes work.

Consider a collection where each document contains a numeric “score” field that is indexed. We want to retrieve every document with a “score” field value that’s less than or equal to forty.

MongoDB uses indexes to quickly locate and retrieve all documents that match a query, in this case, documents containing score fields with a numeric value less than 40.

In MongoDB we can also create compound indexes, which allow us to optimize operations that filter on multiple fields.

For example, we can add a field named “userid,” and then create a compound index on the “userid” and “score” fields.

MongoDB stores the values of indexed fields using an optimized data structure called a B-tree.

A B-tree is a self-balancing tree data structure that is well-suited for general database indexing.

B-trees are sometimes confused with binary trees. But, unlike binary trees, nodes within a B-tree can have more than two child nodes.

B-trees sort their stored data in ascending sequential order, from left to right.

Now let’s traverse a B-tree just as a compound index would. This will give us a better understanding of how compound indexes work internally and how equality, sort, and range play a role in formulating the order of an index.

For this example, we’ll use a dataset of five documents with a similar structure as before that contains a userid, username, and a score field.

We want to retrieve every document with a userid field value between 2 and 4, and a username field value of “anonymous”.

To support this query, we create a compound index on the userid and username fields.

MongoDB will use a B-tree similar to this diagram in support of this index.

Because userId is the first field of our index definition, it acts as an index prefix that prompts MongoDB to first process the userid range filter portion of our query.

Once MongoDB finishes processing the first part of the query, it moves on to the next key in our index, which is the username field.It starts at the first node with a userid of two or greater and checks each node of the B-tree to determine if the value of the username field is “anonymous”.

It appears that we have encountered a node with the username Sam.

This means that MongoDB scanned more documents than it needed to. One document doesn’t seem so bad, but imagine if this issue scaled to millions of documents.

Let’s see what happens if we reorder the index keys. Here, we’ve reordered the index so that the first field of the index definition is the username, and the second field is the userid.

With this new index our b tree will resemble something like this.

Now, we first do an exact match on the username, and then traverse the tree where anonymous usernames are on the left of the tree.

Once that’s complete, we start from the first anonymous user with an userId of 2 or greater, and begin traversing the tree, returning any nodes that fall within the userid range of 2 to 4.

By reordering the index keys we have reduced the number of documents MongoDB needs to read thereby improving the performance of our query.

Now, let’s say that we also want to sort the query using the “score” field. Let’s update our index by adding the score key to the end.

Our B tree has now been updated to account for the score field.

Let’s traverse the B-tree again to see what happens.

Like before, we first match on username and then the range query on userid.

If we traverse the tree from left to right again, we’ll see that our results are not correctly sorted by the score field values. For example, here we see that the scores are not in the correct order.

This means that our index is not supporting our query’s sort operation, which forces MongoDB to do an in-memory sort. This takes time and resources.

To fix this, let’s move our score key before the userid key in the index.

Now our B tree will look a bit different from before.

When we traverse the tree, all of the scores are sorted correctly according to our query, without having to do an in-memory sort.

We still had to visit one extra node but avoiding the in-memory sort is worth it.

Awesome job! In this video, you learned how MongoDB stores indexes in easily accessible blocks of data in a B-tree data structure.

Then you saw how MongoDB traverses a B-tree to efficiently retrieve data by using an index.

You also learned what compound indexes are and the recommended order in which to arrange the fields of a compound index.