Last active
March 27, 2023 18:18
-
-
Save nol166/02903a874befb8d3934cdd0153e7a621 to your computer and use it in GitHub Desktop.
Get query execution stats in mongosh
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
// Add to ~/.mongoshrc.js | |
// getExectionTime(<query>, <collection>, [hint]) | |
// Usage example: getExecutionTime({ "name": "John" }, "users", { "name": 1 }) | |
const getExecutionTime = (query, coll, hint = null) => { | |
hint ? console.log("Using hint: ", hint) : null; | |
query ? console.log("Using query: ", query) : null | |
currentDB = db.getName(); | |
if (currentDB === "admin" || currentDB === "test") { | |
throw new Error("Cannot run getExecutionTime() in admin or test databases") | |
} | |
currentDB ? console.log("On database: ", currentDB) : null; | |
coll = db.getCollection(coll); | |
let result; | |
hint | |
? result =coll.find(query).hint(hint).explain("executionStats") | |
: result = coll.find(query).explain("executionStats"); | |
return result.executionStats.executionTimeMillis; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment