Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 29, 2014 07:54
Show Gist options
  • Save saintc0d3r/d371229bb19648248bd0 to your computer and use it in GitHub Desktop.
Save saintc0d3r/d371229bb19648248bd0 to your computer and use it in GitHub Desktop.
Telling mongodb to use specific index when doing a query
// Let's say there is foobar db which have foo collection with some documents in it
use foo
var i = 0
for(i=0;i < 100;i++)(db.bar.insert({'a':i, 'b':i, 'c':i, 'd':i}))
// and we create indexes for each field
db.bar.ensureIndex({'a':1})
db.bar.ensureIndex({'b':1})
db.bar.ensureIndex({'c':1})
db.bar.ensureIndex({'d':1})
db.bar.getIndexes()
// Let's query a document while telling the server to use index c:1
db.bar.find({'a':50, 'b':50,'c':50}).hint({'c':1})
// What about if we telling the server to not use any index when doing the above query ?
db.bar.find({'a':50, 'b':50,'c':50}).hint({$natural:1})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment