Database Reference
In-Depth Information
The results returned here show that some queries are taking longer than 0ms (remember the quote at the
beginning of the chapter).
Next, you want to reconstruct the query for the first (and worst-performing) query, so you can see what is being
returned. The preceding output indicates that the poorly performing query is querying blog.posts and that the query
term is {Tags:"even"} . Finally, you can see that this query is taking a whopping 15ms to execute.
The reconstructed query looks like this:
>db.posts.find({Tags:"even"})
{ "_id" : ObjectId("4c727cbd91a01b2a14010000"), "author" : ObjectId("4c637ec8b8642fea02000000"),
"Title" : "Completly fake blogpost number 2", "Message" : "Some fake text to create a database of
blog posts", "Tags" : [ "blog", "post", "even", "tag2" ] }
{ "_id" : ObjectId("4c727cbd91a01b2a14030000"), "author" : ObjectId("4c637ec8b8642fea02000000"),
"Title" : "Completly fake blogpost number 4", "Message" : "Some fake text to create a database of
blog posts", "Tags" : [ "blog", "post", "even", "tag4" ] }
{ "_id" : ObjectId("4c727cbd91a01b2a14050000"), "author" : ObjectId("4c637ec8b8642fea02000000"),
"Title" : "Completly fake blogpost number 6", "Message" : "Some fake text to create a database of
blog posts", "Tags" : [ "blog", "post", "even", "tag6" ] }
...
This output should come as no surprise; this query was created for the express purpose of demonstrating how to
find and fix a slow query.
The goal is to figure out how to make the query run faster, so use the explain() function to determine how
MongoDB is performing this query:
> db.posts.find({Tags:"even"}).explain()
{
"cursor" : "BasicCursor",
"isMultiKey" : false,
"n" : 14997,
"nscannedObjects" : 29997,
"nscanned" : 29997,
"nscannedObjectsAllPlans" : 29997,
"nscannedAllPlans" : 29997,
"scanAndOrder" : false,
"indexOnly" : false,
"nYields" : 0,
"nChunkSkips" : 0,
"millis" : 27,
"indexBounds" : {
},
"server" : "Pixl.local:27017"
}
You can see from the output here that the query is not using any indexes. The explain() function shows that the
query is using a “ BasicCursor ”, which means the query is just performing a simple scan of the collection's records.
Specifically, it's scanning all the records in the database one by one to find the tags (all 9999 of them); this process
takes 27ms. That may not sound like a long time, but if you were to use this query on a popular page of your website, it
would cause additional load to the disk I/O, as well as tremendous stress on the web server. Consequently, this query
would cause the connection to the web browser to remain open longer while the page is being created.
 
Search WWH ::




Custom Search