O'Reilly logo

MongoDB and Python by Niall O'Higgins

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fast Lookups: Using Indexes with MongoDB

The role of indexes in MongoDB is very similar to their role in traditional RDBMS such as MySQL, PostgreSQL, etc. MongoDB offers two kinds of indexes out-of-the-box: Btree indexes and geospatial indexes. The btree indexes in MongoDB are much the same as the equivalents in MySQL or PostgreSQL. When in a relational system you would put an index on a column to get fast lookups on that field, you do an analogous thing in MongoDB by placing an index on a particular property in a collection. Just as with an RDBMS, MongoDB indexes can span multiple fields (a.k.a. compound indexes)—useful if you know in advance that you will be querying based on the value of more than a single property. A compound index would be useful for example if you were querying documents by first name and last name. In MongoDB, btree indexes can have a “direction”. This direction is only useful in the case of compound indexes, where the index direction should match the sort direction or range query direction for optimal performance. For example, if you are querying a range (say, A through C) on first name and last name and then sorting in ascending order on last name, your compound index direction should also be ascending.

Using a btree index will incur a performance hit on writes, as the database must now update the index in addition to the data. For this reason, it is wise to choose your indexes carefully. Avoid superfluous indexes if at all possible. Indexes also take up ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required