MongoDB has a bundled query profiler that can be run in a development environment or even on production databases. As it is customary for MongoDB, the API exposed by the profiler is a collection, which is composed of one document for each captured query.

Here's how you profile a section of your application:

mongo --eval 'db.setProfilingLevel(0); db.system.profile.drop(); db.setProfilingLevel(2);'
mongo --eval 'db.setProfilingLevel(0);'

First of all, we disable any lingering profiling directive and drop the system.profile capped collection (as the only way to empty it). Then we enable profiling either of:

- all queries, with db.setProfilingLevel(2). This setting can be used to count and group the most frequent queries in development.

- Of the subset of slow queries, with db.setProfilingLevel(1). This setting can be active in production without a significant loss of performance.

Queries are considered slow if they take longer than 100 milliseconds. This parameter is set in the MongoDB configuration as:

- slowms in MongoDB 2.2 and 2.4;

- operationProfiling.slowOpThresholdMs in MongoDB 2.6.

After running a typical transaction on your application, we disable profiling again with db.setProfilingLevel(0) to avoid our own subsequent operations to be registered too.

The results of profiling are logged in the mongod log, but a more versatile API is to query the db.system.profile collection directly:

		"op" : "insert",
		"ns" : "test.items",
		"query" : {
			"_id" : ObjectId("53960db40dbae4d4d9fd0275"),
			"key" : "car",
			"value" : 20
		"ninserted" : 1,
		"keyUpdates" : 0,
		"numYield" : 0,
		"lockStats" : {
			"timeLockedMicros" : {
				"r" : NumberLong(0),
				"w" : NumberLong(1509)
			"timeAcquiringMicros" : {
				"r" : NumberLong(0),
				"w" : NumberLong(6)
		"millis" : 1,
		"execStats" : {
		"ts" : ISODate("2014-06-09T19:40:36.731Z"),
		"client" : "",
		"allUsers" : [ ],
		"user" : ""

Giorgio Sironi

Developer at Onebip , Website , Git home page , @giorgiosironi , Linkedin profile
I search for the harmony between form and context, which is a fancy way of saying I build software to fit in the world I'm in and its rapid changes. In the specific, my areas of expertise are testing, OOP design and distributed computing.

All articles by Giorgio Sironi


comments powered by Disqus


Follow Us