Last active
December 5, 2016 14:01
-
-
Save belsrc/6211ef753f2e7cd1e6f944e6e8e0a943 to your computer and use it in GitHub Desktop.
Check Mongo query performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
db.setProfilingLevel(2) Needs to be ran first | |
0 - Off | |
1 - Only slow | |
2 - all | |
This enables query profiling, after enabling profiling, run the application for a bit to get some data. | |
*/ | |
db.getCollection('system.profile') | |
.find({ | |
op: 'query', | |
$and: [ | |
{ ns: { $ne: 'DATABASE-NAME.system.profile' }}, | |
{ ns: { $ne: 'DATABASE-NAME.system.namespaces' }}, | |
{ ns: { $ne: 'DATABASE-NAME.system.indexes' }} | |
]}, | |
{ ns: 1, query: 1, nscannedObjects: 1, nreturned: 1, ts: 1 } | |
) | |
.sort({ ts: -1 }) | |
// Looking for nscannedObjects & nreturned to be 1:1, or close to it | |
// If the number of scans is larger than the number of returned, you may need an index | |
/* | |
Response will be somethig like: | |
{ | |
"ns" : "DATABASE-NAME.collection-name", | |
"query" : { | |
"orderby" : { | |
"type" : 1 | |
}, | |
"$query" : { | |
"is_deleted" : false | |
} | |
}, | |
"nscannedObjects" : 34, | |
"nreturned" : 34, | |
"ts" : ISODate("2016-10-26T14:39:46.504Z") | |
} | |
*/ | |
// In later versions of Mongo (3.2 i believe), this query changes slightly. | |
db.getCollection('system.profile') | |
.find({ | |
op: 'query', | |
$and: [ | |
{ ns: { $ne: 'DATABASE-NAME.system.profile' }}, | |
{ ns:{ $ne: 'DATABASE-NAME.system.namespaces' }}, | |
{ ns: { $ne: 'DATABASE-NAME.system.indexes' }} | |
]}, | |
{ ns: 1, query: 1, keysExamined: 1, docsExamined: 1, nreturned: 1, ts: 1 } | |
) | |
.sort({ ts: -1 }) | |
// And you are comparing docsExamined and nreturned. This can also be used with... | |
db.getCollection('COLLECTION_NAME').aggregate( [ { $indexStats: { } } ] ) | |
// To determine if a current index is actually needed (Mongo 3.2) by looking at the 'ops' field in the returned value. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment