0
0
MongoDBquery~5 mins

Profiler for slow queries in MongoDB

Choose your learning style9 modes available
Introduction

The profiler helps find slow database queries so you can make your app faster.

When your app feels slow and you want to see which database queries take the most time.
When you want to check if a new feature causes slow database access.
When you want to improve database performance by fixing slow queries.
When you want to monitor database activity during peak hours.
When you want to learn how your database is used in real time.
Syntax
MongoDB
db.setProfilingLevel(level, { slowms: milliseconds })

// To check current profiling level and slowms
db.getProfilingStatus()

// To see slow queries recorded
db.system.profile.find({ millis: { $gt: threshold } })

level can be 0 (off), 1 (slow queries), or 2 (all queries).

slowms sets the threshold in milliseconds to consider a query slow.

Examples
Turn on profiling for queries slower than 100 milliseconds.
MongoDB
db.setProfilingLevel(1, { slowms: 100 })
Turn off profiling to stop recording queries.
MongoDB
db.setProfilingLevel(0)
Check current profiling level and slow query threshold.
MongoDB
db.getProfilingStatus()
Find and list queries that took more than 200 milliseconds, sorted by slowest first.
MongoDB
db.system.profile.find({ millis: { $gt: 200 } }).sort({ millis: -1 })
Sample Program

This example turns on profiling for queries slower than 50 ms, runs a query, then fetches slow queries from the profiler.

MongoDB
db.setProfilingLevel(1, { slowms: 50 })

// Run a sample slow query
db.orders.find({ price: { $gt: 1000 } }).toArray()

// Check slow queries recorded
const slowQueries = db.system.profile.find({ millis: { $gt: 50 } }).sort({ millis: -1 }).toArray()
slowQueries
OutputSuccess
Important Notes

Profiling can slow down your database, so use it only when needed.

Remember to turn off profiling (level 0) after you finish to avoid extra load.

The profiler stores data in the system.profile collection inside your database.

Summary

The profiler helps find slow queries by recording them.

Set profiling level and slowms threshold to control what is recorded.

Check system.profile collection to see slow queries and improve performance.