Database Reference
In-Depth Information
■
if you see a detailed query explanation that shows a significantly larger number of scanned records (
nscanned
)
than it returns (
n
), then that query is probably a candidate for indexing.
Note
The next step is to determine whether adding an index on the
Tags
field improves the query's performance:
> db.posts.ensureIndex({Tags:1})
Now run the
explain()
function again to see the effect of adding the index:
> db.posts.find({Tags:"even"}).explain()
{
"cursor" : "BtreeCursor Tags_1",
"isMultiKey" : true,
"n" : 14997,
"nscannedObjects" : 14997,
"nscanned" : 14997,
"nscannedObjectsAllPlans" : 14997,
"nscannedAllPlans" : 14997,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 4,
"indexBounds" : {
"Tags" : [
[
"even",
"even"
]
]
},
"server" : "Pixl.local:27017"
}
The performance of the query has improved significantly. You can see that the query is now using a
BtreeCursor
driven by the
Tags_1
index. The number of scanned records has been reduced from 29,997 records to the same 14,997
records you expect the query to return, and the execution time has dropped to 4ms.
■
the most common index type, and the only one used by mongoDB, is the btree (binary-tree). a
BtreeCursor
is
a mongoDB data cursor that uses the binary tree index to navigate from document to document. Btree indexes are very
common in database systems because they provide fast inserts and deletes, yet also provide reasonable performance
when used to walk or sort data.
Note