Skip to content

Instantly share code, notes, and snippets.

@nol166
Last active March 27, 2023 18:18
Show Gist options
  • Save nol166/02903a874befb8d3934cdd0153e7a621 to your computer and use it in GitHub Desktop.
Save nol166/02903a874befb8d3934cdd0153e7a621 to your computer and use it in GitHub Desktop.
Get query execution stats in mongosh
// 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