Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 29, 2014 10:52
Show Gist options
  • Save saintc0d3r/d91f96ee9adad419072d to your computer and use it in GitHub Desktop.
Save saintc0d3r/d91f96ee9adad419072d to your computer and use it in GitHub Desktop.
Using hint to increase specific query's performance on indexed collections
// Suppose, we have 10000000 documents stored in bar collections (foo database)
use foo
for(var i = 0; i< 10000000; i++)(db.bar.insert({'a':i, 'b':i, 'c':i}))
// We create indexes for them
db.bar.ensureIndex({'a':1})
db.bar.ensureIndex({'b':1})
db.bar.ensureIndex({'c':1})
db.bar.ensureIndex({'a':1, 'b':1,'c':1})
// Let query a number of document using $gt, $lt, sort the result & explain it. Note the number of scanned document & milis.
db.bar.find({'a':{$gt:500}, 'b':{$lt:500000}, 'c': 350555}).sort({'a':1}).explain()
// Let's use hint to speed up the above query. We'll hint 'a' 1st and see what happen next
db.bar.find({'a':{$gt:500}, 'b':{$lt:500000}, 'c': 350555}).sort({'a':1}).hint({'a':1}).explain()
// It was slightly better. What about we hint 'b' now
db.bar.find({'a':{$gt:500}, 'b':{$lt:500000}, 'c': 350555}).sort({'a':1}).hint({'b':1}).explain()
// Looks better. Let's hint 'c'
db.bar.find({'a':{$gt:500}, 'b':{$lt:500000}, 'c': 350555}).sort({'c':1}).hint({'b':1}).explain()
// Perfect ! Now, we should understand which index we should hint to increase our query's performance :D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment