tableflip / how-to

:question: How to TABLEFLIP and other stories
4 stars 0 forks source link

How to debug Mongo slow queries #22

Open alanshaw opened 7 years ago

alanshaw commented 7 years ago

Is Mongo hogging all your CPU? It's probably because it's doing a lot of work to find your documents. This usually equates to adding an index to your collection.

Turn on profiling:

mongo
use dbname
// 0 = off, 1 = profile slow queries, 2 = profile all queries
// https://docs.mongodb.com/v3.2/tutorial/manage-the-database-profiler/#profiling-levels
db.setProfilingLevel(1) 

Get the latest profile:

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

The important fields are the time taken, document examined and the query that was performed. Examining the query should give you an idea of what index(es) need to be added.

Note: Apply new indexes in a database migration, not directly on the server