Databases Reference
In-Depth Information
The output should be as follows:
{
“cursor” : “BasicCursor”,
“nscanned” : 1000209,
“nscannedObjects” : 1000209,
“n” : 2077,
“millis” : 484,
“indexBounds” : {
}
}
At this stage it's evident that the query is not running optimally because the nscanned and
nscannedObjects count reads 1,000,209, which is all the documents in the collection. This is a
good point to introduce indexes and optimize things.
CREATING AND USING INDEXES IN MONGODB
The ensureIndex keyword does most of the index creation magic in MongoDB. The last query
fi ltered the ratings collection based on the movie_id so creating an index on that property should
transform the lookup from table scan to B-tree index traversal. First, verify if the theory does
hold good.
Create the index by running the following command:
db.ratings.ensureIndex({ movie_id:1 });
Available for
download on
Wrox.com
movielens_indexes.txt
This creates an index on movie_id and sorts the keys in the index in an ascending order. To create
an index with keys sorted in descending order use the following:
db.ratings.ensureIndex({ movie_id:-1 });
Available for
download on
Wrox.com
movielens_indexes.txt
Then rerun the earlier query as follows:
db.ratings.find({movie_id: 1});
Available for
download on
Wrox.com
movielens_indexes.txt
Search WWH ::




Custom Search