MongoDB - Profiling Slow Queries

Expensive queries can impact overall performance. By adding an index to a column being used in a query, it can significantly improve overall query times. Here's a guide for profiling the database.

First, connect to the database using the mongo shell. If you're not already in the target database, then run:

use database_name;

Next, turn on the profiler, specifying the number of milliseconds required for a query to be logged:

db.setProfilingLevel(1, 300); // logs anything slower than 300ms

Finally, to display the last 10 logged queries, do:

db.system.profile.find().limit(10).sort( { ts : -1 } ).pretty()

When you're done, be sure to turn off the profiler: