Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created June 28, 2014 11:59
Show Gist options
  • Save saintc0d3r/46655213dd93b63cba0b to your computer and use it in GitHub Desktop.
Save saintc0d3r/46655213dd93b63cba0b to your computer and use it in GitHub Desktop.
Understanding Explain in related to mongodb's index
// Let's say that there is a 'foo' collection has 10 mill documents in it
use foobar
for(var i=0;i<10000000;i++){db.foo.insert({'a':i,'b':i,'c':i})}
// Then, we'll add indexes for a,b,c on the 'foo' collection
db.foo.ensureIndex({'a':1, 'b':1, 'c':1})
// Let's do querying a doco by a field as the search criteria then note the millis value in the displayed result
db.foo.find({'a': 5678545}).explain()
// Now, let's create an index for field a and then redo the above query. Note the millis value.
db.foo.ensureIndex({'a': 1})
db.foo.find({'a': 5678545}).explain()
// Drop the prior index and create a new compound index
db.foo.dropIndex({'a':1})
db.foo.ensureIndex({'a':1, 'b':1, 'c':1})
// Let's query a document by b or c as the field criteria and note the Cursor & milis values
db.foo.find({'b':5000}).explain()
// And query for a document which specify a , at least as the query's criteria. Make note the cursor, indexBounds & milis values.
db.foo.find({'a':5000}).explain()
// Let's query a document by specified a. But this time, we'll tell mongodb to only return a only & exlude _id key.
// Notice the cursor, milis, indexbounds & indexOnly
db.foo.find({'a':5000}, {'a':1, 'b':1, '_id':0}).explain()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment