Introduction to MongoDB Indexing

Introduction

This article explains how to use an index to speed up our queries with a practical example.

Objective

The objective of this article is to learn how to use an index to speed up our queries.

First let us assume we have a collection named foo and we want to find all the collections with 10 for the value of the field x.

So we say:
  1. db.foo.find({ x :10})   
Now let us think, what does the server do to find the document?
The server will visit each and every document and check the value of x is equal to 10 and if so return it. That's an over-simplification but it shows us the problem. We will need to scan every location on disk to dig up every document and compare the value of the field x. That is a very, very slow operation and if we want to do it quickly then we need to find a better strategy. Indexing is done by Mongo by storing all the documents in its own location on disk. An index logically holds a mapping to those locations from field values. In the preceding example an index on field x of the collection foo has an entry of each possible value of x associated with a list of document locations and each of those documents contain a value or key. So for example we have a bunch of documents with x equaling 9 and x equaling 10.
 
 
We will design a query to find the documents where the field x matches the value 10. Mongo will look in the index to find the entry whose value is 10 and jump directly to that document. This is much much faster than scanning the entire disk and much much faster than loading each and every document.
Indexes in Mongo
 Regular Indexes
 
The regular index is an index that we can use on a single or multiple field with multiple values as well.
 
 Compound Indexes
 
   A compound index includes more than one field of the documents in a collection.
 
 Multikey Indexes
 
 A multikey index references an array and records a match if a query includes any value in the array. 
 
 Geo Indexes
 
 The geo index is optimized for geographical queries. This supports proximity of points to the center.

 Text Indexes
 
Text indexes allows us to do the things like search engines do, parsing text queries and comparing them against text fields.

 Time to Live Index
 
This supports Expiring documents using a TTL index we can designate a date time field on our document to be an expiration date and Mongo will automatically remove the document from our collection when it expires. This again reduces our overhead in writing all kind of patch works in removing our self.
 
Summary
 
 In this article we learned Indexing for a Mongo db.
 
 


Similar Articles