Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find slow queries in mongo DB

A few show tricks to find slow queries in mongodb

Enable profiling

First, you have to enable profiling

> db.setProfilingLevel(1)

Now let it run for a while. It collects the slow queries ( > 100ms) into a capped collections, so queries go in and if it's full, old queries go out, so don't be surprised that it's a moving target...

Histogram of the slowest collections (collections with the slowest queries) - number of queries per collection

This presents a histogram of slow collections

> db.system.profile.group({key: {ns: true}, initial: {count: 0}, reduce: function(obj,prev){ prev.count++;}})

Histogram of the slowest collections (collections with the slowest queries) - number of millies spent in each collection

> db.system.profile.group({key: {ns: true}, initial: {millis: 0}, reduce: function(obj, prev){ prev.millis += obj.millis;}})

Find the most recent slow query

> db.system.profile.find().sort({$natural: -1}).limit(1)

Find the single slowest query in the capped system.profile collection right now

> db.system.profile.find().sort({millis: -1}).limit(1)
@rantav

This comment has been minimized.

Copy link
Owner Author

@rantav rantav commented Aug 23, 2012

@poxaV

This comment has been minimized.

Copy link

@poxaV poxaV commented Apr 15, 2016

It would be much easier to cut & paste if the "> " was removed from the example mongo shell commandline.

@vn971

This comment has been minimized.

Copy link

@vn971 vn971 commented Mar 23, 2017

@poxaV, yeah, agree. Made my fork to remove these letters though, no problem. It's git..

@congthang1

This comment has been minimized.

Copy link

@congthang1 congthang1 commented Dec 20, 2019

please add .pretty() lol

@benjamingr

This comment has been minimized.

Copy link

@benjamingr benjamingr commented Jan 13, 2020

Thanks! @rantav

Also apparently after talking to Mongo Atlas they said db.setProfilingLevel(1) can pretty much decimate our cluster 🤷‍♂️

@MarkEmerson

This comment has been minimized.

Copy link

@MarkEmerson MarkEmerson commented Nov 3, 2020

good start but caution!

ensure you set profiling back to : db.setProfilingLevel( 0, 100 )

else you can watch your disk space grow in gigabytes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment