MongoDB - Indexing



What is index in MongoDB ?

MongoDB provides several of the best data structures for indexing, such as the classic B-tree, and other additions such as two-dimensional and spherical GeoSpatial indexes.

Whenever a new collection is created, Mongo automatically creates an index
by the _id. These indexes can be found in the system.indexes collection. The following query shows all indexes in the database:

>db.system.indexes.find()

Most queries will include more fields than just the _id, so we need to make
indexes on those fields.

To increase the performance, you need to create index on display filed/s. But before that we need to check if it will improve speed or not. To check that, first check the query without an index. The explain() method is used to output details of a given operations.

>db.phones.find({display: "+1 800-5650001"}).explain()
{
"cursor" : "BasicCursor",
"nscanned" : 109999,
"nscannedObjects" : 109999,
"n" : 1,
"millis" : 52,
"indexBounds" : {
}
}

millis : This filed will give you the time in milliseconds to complete the query.
cursor: B-Tree is a most optimal cursor

We create an index by calling ensureIndex(fields, options) on the collection.

>db.phones.ensureIndex({ display : 1 },{ unique : true, dropDups : true })


In production, you should always build indexes in the background using the 
{ background : 1 } option.

>db.phones.ensureIndex({ "components.area": 1 }, { background : 1 })

explain() is a useful function, but you’ll use it only when testing specific query
calls. 
If you need to profile in a normal test or production environment, you’ll
need the system profiler.
Let’s set the profiling level to 2 (level 2 stores all queries; profiling level 1
stores only slower queries greater than 100 milliseconds) and then run find()
as normal.

>db.setProfilingLevel(2)
>db.phones.find({ display : "+1 800-5650001" })

Comments

Popular posts from this blog

MongoDB - Sharding