Slow Query Analysis
Built-in Profiler
MongoDB provides a built-in query profiler, enabled via db.setProfilingLevel(n,m) command.
Profiler Level Settings
- Level 0 (profiling off):
db.setProfilingLevel(0) - Level 1 (record slow queries):
db.setProfilingLevel(1, m)- m is millisecond threshold - Level 2 (record all operations):
db.setProfilingLevel(2)
Usage Example
// Set to record queries slower than 50ms
db.setProfilingLevel(1, 50)
// View profiling data
db.system.profile.find().sort({ts:-1}).limit(10)
Database Performance Problem Analysis
-
Unreasonable application design
- Frequent short connections
- Unoptimized SQL queries
- N+1 query problem
-
Incorrect data types
- Field type doesn’t match actual data
-
Hardware configuration issues
- CPU, memory, disk I/O insufficient
-
Missing indexes
- Frequently executing full table scans
EXPLAIN Basic Concepts
Output Fields
- id: Sequence number of SELECT operation in query
- type: Table access method (best to worst: system > const > eq_ref > ref > range > index > ALL)
- possible_keys: Possible indexes to use
- key: Actually used index
- rows: Estimated number of rows to examine
Common Optimization Scenarios
- Full table scan (type=ALL): Add appropriate indexes
- File sort (Using filesort): Add indexes for ORDER BY columns
- Temporary table (Using temporary): Optimize GROUP BY queries
- Index cover (Using index): Good situation