Database Reference
In-Depth Information
// Even numbered blogs
$blogpost['Tags'] = array("blog", "post", "even", "tag{$i}");
}
$db->posts->insert($blogpost);
}
?>
This program finds the first author in the
blog
database's
authors
collection, and then pretends that the author
has been extraordinarily productive. It creates 10,000 fake blog postings in the author's name, all in the blink of an eye.
The posts are not very interesting to read; nevertheless, they are alternatively assigned
odd
and
even
tags. These tags
will serve to demonstrate how to optimize a simple query.
The next step is to save the program as
fastblogger.php
and then run it using the command-line PHP tool:
$php fastblogger.php
Next, you need to enable the database profiler, which you will use to determine whether you can improve the
example's queries:
$ mongo
> use blog
switched to db blog
> show collections
authors
posts
...
system.profile
tagcloud
...
users
> db.setProfilingLevel(2)
{ "was" : 0, "slowms" : 100, "ok" : 1 }
Now wait a few moments for the command to take effect, open the required collections, and then perform its
other tasks. Next, you want to simulate having the blog website access all of the blog posts with the
even
tag. Do so by
executing a query that the site can use to implement this function:
$Mongo
use blog
$db.posts.find({Tags:"even"})
...
If you query the
profiler
collection for results that exceed 5ms, you should see something like this:
>db.system.profile.find({millis:{$gt:5}}).sort({millis:-1})
{ "op" : "query", "ns" : "blog.posts", "query" : { "tags" : "even" }, "ntoreturn" : 0, "ntoskip" :
0, "nscanned" : 19998, "keyUpdates" : 0, "numYield" : 0, "lockStats" : { "timeLockedMicros" : { "r"
: NumberLong(12869), "w" : NumberLong(0) }, "timeAcquiringMicros" : { "r" : NumberLong(5), "w" :
NumberLong(3) } }, "nreturned" : 0, "responseLength" : 20, "millis" : 12, "ts" : ISODate("2013-05-
18T09:04:32.974Z"), "client" : "127.0.0.1", "allUsers" : [ ], "user" : "" }...