Performance Tools and Techniques / Performance Tools for Profiling Queries
Code Recap: Performance Tools for Profiling Queries
db.setProfilingLevel()
The setProfilingLevel()
method enables query profiling for the database. The level determines how the profiler acts. The available levels are:
- 0 - Profiling is disabled
- 1 - The profiler only records operations that exceed the
slowms
threshold value (default: 100ms) - 2 - All operations are recorded. (Not recommended for production systems)
This example sets the profiler to record all operations that exceed the default slowms
threshold.
db.setProfilingLevel(1)
This example sets the profiler to record all operations that exceed 150 milliseconds in duration.
db.setProfilingLevel(1, {slowms: 150 });
Using db.system.profile.find()
The db.system.profile
collection in MongoDB contains profiling data about database operations, such as queries, writes, and commands executed. The find()
method lets you query this profiling data and analyze detailed metrics about how operations are performed. Profiling data can include the execution time (millis
), namespace (ns
), operation type (op
), documents examined (docsExamined
), keys examined, query filters (filter
), and more. This is useful for diagnosing and optimizing performance issues.
This example retrieves profiling records where the operation took more than 100ms. The .pretty()
method formats the output for readability.
db.system.profile.find(
{millis: {$gt: 100}}
).pretty()
{
op: 'query',
ns: 'sample_airbnb.listingsAndReviews_big_collection',
command: {
find: 'listingsAndReviews_big_collection',
filter: {
property_type: 'House',
room_type: 'Entire home/apt',
minimum_nights: { '$gt': '2' },
maximum_nights: { '$lte': '30' },
bedrooms: { '$gte': 2 }
. . .
},
cursorid: Long('2735269190803785067'),
keysExamined: 0,
docsExamined: 7171,
nBatches: 1,
numYield: 30,
nreturned: 101,
. . .
millis: 575,
planSummary: 'COLLSCAN',
. . .
}