0
0
MongodbHow-ToBeginner · 3 min read

How to Enable Profiling in MongoDB: Syntax and Examples

To enable profiling in MongoDB, use the db.setProfilingLevel(level, slowms) command where level can be 0 (off), 1 (slow operations), or 2 (all operations). You can also specify slowms to set the threshold in milliseconds for slow queries to be logged.
📐

Syntax

The db.setProfilingLevel() method controls the profiling level for the current database.

  • level: 0 disables profiling, 1 logs slow operations, 2 logs all operations.
  • slowms (optional): sets the threshold in milliseconds for slow operations to be logged when level is 1.
mongodb
db.setProfilingLevel(level, slowms)
💻

Example

This example enables profiling to log all operations and then sets it to log only slow operations taking longer than 100 milliseconds.

mongodb
use mydatabase
// Enable profiling for all operations
db.setProfilingLevel(2)

// Later, enable profiling only for slow operations over 100ms
db.setProfilingLevel(1, 100)
Output
{ "was" : 0, "slowms" : 100, "ok" : 1 }
⚠️

Common Pitfalls

Common mistakes include:

  • Setting profiling level to 2 in production without monitoring can cause performance issues.
  • Not specifying slowms when using level 1, which defaults to 100ms.
  • Forgetting to switch profiling off (level 0) after debugging, which can fill logs quickly.
mongodb
/* Wrong: Enabling profiling level 2 without caution */
db.setProfilingLevel(2)

/* Right: Enable level 1 with a slowms threshold */
db.setProfilingLevel(1, 200)
📊

Quick Reference

Profiling LevelDescriptionEffect
0OffNo profiling data is collected
1Slow operationsLogs operations slower than slowms milliseconds
2All operationsLogs all database operations

Key Takeaways

Use db.setProfilingLevel(level, slowms) to control profiling in MongoDB.
Level 0 disables profiling, level 1 logs slow queries, and level 2 logs all queries.
Set slowms to define what counts as a slow operation when using level 1.
Avoid enabling level 2 profiling in production without monitoring due to performance impact.
Remember to disable profiling after troubleshooting to prevent large log files.