Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save saintc0d3r/437a4a367d8fc9a7b38e to your computer and use it in GitHub Desktop.

Select an option

Save saintc0d3r/437a4a367d8fc9a7b38e to your computer and use it in GitHub Desktop.
Muilti key Indexes on mongodb
// Let's say we have a database named as 'foo'
use foo
// On the foo database, there is a collection named as 'bar' & we'll add a record on 'bar' collection
db.bar.insert({'a':1, 'b':5})
// Now, we are going to add indexes for both a & b
db.bar.ensureIndex({'a':1, 'b': -1})
// Let's see which index the bar uses when querying it a or/and b. Notice what is the values of "cursor" & "isMultiKey" in the returned result
db.bar.find({'a':50, 'b':20}).explain()
// Next, let's insert a document where a's value is an array
db.bar.insert({'a':[1,2,3], 'b':4})
// Then, let's query them and also explain to us what does it do ( notice the "cursor" & "isMultiKey" properties in the result)
db.bar.find({'a':1}).explain()
// Finally, let's add a new document, where both a & b contain array values. See how it goes later
db.bar.insert({'a':[4,5], 'b':[7,8,9]})
// Supposed, we have a new document that has property 'c' where 'c' contain array of 'd's
db.bar.insert({'a':2, 'b':7, 'c': [{'d':1}, {'d':2},{'d':3},{'d':4}]})
// Next, let's add indexes to a,b & c.d
db.bar.ensureIndex({'a':1, 'b':1, 'c.d':1})
// Let's query them again
db.bar.find({'a':{$in:[1,2]}, 'b':{$gt:3}, 'c.d':1})
// Explain what does the prior query did ( notice the "cursor" & "isMultiKey" properties in the result)
db.bar.find({'a':{$in:[1,2]}, 'b':{$gt:3}, 'c.d':1}).explain()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment