MongoDB
Indexing & Query
Optimization
Overview
• Indexing
• Profiling your queries
• Creating indexes
• Managing indexes
What is an Index?
A data structure that can used to make certain
query more efficient ?
Table scans
1 2 3 4 5 6 7
Looked at 7 objects
Find where x equals 7
Tree Lookup
7
6
5
4
3
2
1
Looked at 3 objects
Find where x equals 7
Use explain
query = db.user.find({title:‛Blog‛})
query.explain();
{
"cursor" : "BasicCursor",
"indexBounds" : [ ],
"nscanned" : 57594,
"nscannedObjects" : 57594,
"n" : 3,
"millis" : 108
}
Creating Indexes
Index a field
db.user.ensureIndex( { ‘name’: 1 })
1 = ascending
-1 = descending
Test last query with explain method.
Compound indexes
db.posts.ensureIndex({name: 1, date: -1})
Indexes maintain order index{a:1}
{a: 0, b : 1}
{a: 1, b : 2}
{a: 1, b : 3}
{a: 2, b : 1}
{a: 3, b : 2}
{a: 3, b : 7}
{a: 3, b : 9}
index{a:1,b:-1}
{a: 0, b : 1}
{a: 1, b : 3}
{a: 1, b : 2}
{a: 2, b : 1}
{a: 3, b : 9}
{a: 3, b : 7}
{a: 3, b : 2}
Unique Indexes
db.user.ensureIndex({title: 1}, {unique: true})
Embedded documents
db.user.save({
title: ‚My First blog‛,
comments: [
{author: ‚Ram‛, time : new Date()} ]
});
db.posts.ensureIndex({‚comments.author‛: 1})
Multikeys
{ ‚tags‛:
[‚mongodb‛, ‚cool‛,‛balck]
, ...}
db.posts.ensureIndex({‚tags‛: 1})
Covered Indexes
• New in 1.7.4
• Query can be resolved in index only
• Need to exclude _id from items projected
db.user.ensureIndex({‚title‛: 1})
db.user.find({‚title‛: ‚My blog post:},
{title: 1, _id:0}))
Sparse Indexes
• Included if and only if indexed values is present
• Limited to single field
db.user.ensureIndex({ title : 1} , {sparse :true} )
db.user.save({ name : Rohan})
db.user.save({ name : Ram , title : princes })
Return only Ram
db.user.find ( { title : { $ne : null} } ) .sort({ title : 1} )
Geospatial Indexes
Managing Indexes
Listing indexes
db.user.getIndexes();
Dropping indexes
db.user.dropIndex({tag :1})
Background Building Indexes
db.user.ensureIndex( { … },{background : true} })
Indexing Strategies
Strategies
• The application queries.
• The relative frequency of query in application.
• Current indexes for your application.
• Which indexes most common query use.
• Use indexes to sort query result
• Ensure that your indexes fit entirely in RAM
• Consider Performance when Creating Indexes for Write-
heavy Applications
Review
• Understand your workload
– Profile your queries
– Use explain on the slow ones
• Create indexes for slow operations

Indexing In MongoDB