Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 29, 2014 21:11
Show Gist options
  • Save saintc0d3r/7e5f6d3bb9cce145bfaa to your computer and use it in GitHub Desktop.
Save saintc0d3r/7e5f6d3bb9cce145bfaa to your computer and use it in GitHub Desktop.
Profiling query in MongoDb
// There are 3 levels profilings in mongodb: Lvl 0, 1 & 2.
// Level 0: The profiler is turned off.
// Level 1: The profiler would log slow queries
// Level 2: The profiler would log all queries (good choice for development phase)
// The profiling's settings could be enabled by suppling certain parameters when starting mongod service.
// Here's the example: I want to start mongod & also enable level 1 profiling where it would log any queries that took 10 ms & more
mongod --profile 1 --slowms 10
// Suppose, we have 10000000 documents stored in bar collections (foo database)
use foo
for(var i = 0; i< 10000000; i++)(db.bar.insert({'a':i, 'b':i, 'c':i}))
// Let's pretend that we have an application that accesses foo.bar and perform this query
db.bar.find({'a':506785})
// Beside looking at the command line box that runs mongod,
// we could also profile our mongodb through running this command in the mongo shell:
db.system.profile.find().pretty()
// The returned results are the logged queries that affect whole collections & dbs hosted by your mongod
// What if we want to profile foo.bar collection only and sort the result by timestamp (ascending)?
// Solution: Modify the prior command as follow in the mongo shell
db.system.profile.find({'ns':'foo.bar'}).sort({'ts':1}).pretty()
// Let's run another try: We want to find logs for queries that took more than 10 ms to complete
// the result is sorted by timestamp ( ascending)
db.system.profile.find({'ns':'foo.bar' ,'millis': {$gt: 10}}).sort({'ts':1}).pretty()
// In the mongo shell, we could get current mongod's profiling level & status by running this following commands:
db.getProfilingLevel()
db.getProfilingStatus()
// We could also change the profiling status of current running mongod, in the mongo shell
// Supposed, we want to set the profiling level to 1 and catch anything that took 20 ms or above:
db.setProfilingLevel(1, 20)
// To turn off profiling in mongo shell, you can run this command:
db.setProfilingLevel(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment