Index In MongoDB

In the era of large data set we expect a fast and efficient data processing. When we talk about to query in database than think about a very basic algorithm of searching. We called it Sequential search.

Basic Algorithm of sequential search is to search each and every row or document one by one, its works fine when we have limited no of rows. But think when we have Billion, Trillion, CENTILLION=1 followed by 303 zerosJ, or even more, than we can’t imagine how much time it takes for searching.

So we are using indexes to faster searching, MongoDB indexes works similar like other database systems. Indexes creates another Simplified Dataset which helps MongoDB engine to narrow results.

Scenario:

Let’s take one scenario that we have 1 Lac records in Employee table.
First insert that much record in DB using following script in shell.

This’ll insert lac record in db.
Check by

Operation without Index:

Searching Employee having empId is “emp_99999”;

Query is:

Here we focus some fields.

“cursor” : “BasicCursor” Basic cursor used, it uses default index which is on field “_id”.
“nscanned” : 100000 MongoDB scans 100000 object to find result.
“millis” : 57 Time to execute a query.

You can find more fields detail here. http://docs.mongodb.org/manual/reference/method/cursor.explain/#explain-results

Adding Index

Very general syntax is:

KEY is field on which index being created.
And 1 means Ascending index. If you want descending than use -1.

In our case we are adding index on empId field.
> db.employee.ensureIndex({“empId”: 1});

Operation after Index

Searching Employee having empId is “emp_99999”;

Query is:

Now you can see query needs to scan only one object to find emp_99999, and also it takes <0 millis.  Also cursor used is btreecursor.
Now you understand beauty of index :).

List all Indexes on a Collection

Use below query

You find 2 indexes here one is default index added on _id field and another is added explicitly.

Remove Indexes

Remove particular index

command

output

Remove All Index

this removes all index from given collection expect _id index.

Default Index on _id field

MongoDB collections have default index on _id field, this index is works like unique index.

Compound Index

You can also create index on multiple field.
Command is

Index Statistics

To view statistics about index like size of index, average size of each object and etc.. .
You can use command

Output