Adding Indexes

MongoDB allows you to index fields in your collections so that you can more quickly find documents. When you add an index in MongoDB, a special data structure is created in the background that stores a small portion of a collection’s data and then optimizes the structure of that data to make it faster to find specific documents.

For example, applying an _id index basically creates a sorted array of _id values. Once the index has been created, you get these benefits:

Image When looking up an object by _id, you can perform an optimized search on the ordered index to find the object in question.

Say that you want objects back sorted by ...

Get Node.js, MongoDB, and AngularJS Web Development 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.