I have been reading about indexing in mongoDB to improve query performance. I have found many useful resources online.
From the mongoDB docs here
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect
I understand the above completely.I found another resource which was amazingly helpful here
Here they try to find from_user "paasdude" without an index.
db.tweets.find({'from_user':'paasdude'}).explain();
{
"cursor" : "BasicCursor",
"nscanned" : 51748,
"nscannedObjects" : 51748,
"n" : 35,
"millis" : 40,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
}
}
Here they add an index to the "from-user" field, from my understanding the value "1" means sort it in ascending order.
db.tweets.ensureIndex({'from_user' : 1});
Here they try to find the from_user "paasdude" with an index.
db.tweets.find({'from_user':'paasdude'}).explain();
{
"cursor" : "BtreeCursor from_user_1",
"nscanned" : 35,
"nscannedObjects" : 35,
"n" : 35,
"millis" : 3,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"from_user" : [
[
"paasdude",
"paasdude"
]
]
}
}
It is clear that after adding the index query time went from 40 milliseconds to 3.
My Questions:
Although I understand the concept and need for indexing I don't understand how it actually worked.
By giving the "from_user" field the an index of 1 did it sort all the from_user fields in ascending order?
Does indexing only work in ascending (1) or descending (-1)?
Why by simply adding an index of 1 to the from_user field drop the query time down from 40 to 3 milliseconds?
When should indexes be used?
NOTE: I apologise if this question is off-topic for stack overflow. This is a more conceptual question and I wasn't sure where else to ask it. If you know a better place to ask this question. Please let me know and I will move it.