Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Last active August 29, 2015 14:03
Show Gist options
  • Save saintc0d3r/62c7193b8de0c33959f9 to your computer and use it in GitHub Desktop.
Save saintc0d3r/62c7193b8de0c33959f9 to your computer and use it in GitHub Desktop.
Sparse index on mongodb
// Let's create a tournaments database where it has fighters table with few documents in it
use tournaments
db.fighters.insert({'name':'Ryu', 'ultimate': 'shinkuu hadou ken'})
db.fighters.insert({'name':'Ken', 'ultimate': 'Shoryureppa'})
db.fighters.insert({'name':'Dan'})
db.fighters.insert({'name':'Zangief'})
// We want to put an index on the name & ultimate fields to speed its query by name's performance (no multi key index applied)
db.fighters.ensureIndex({'name':1, 'ultimate':1})
// then, we have thought that we want to put a unique key on the ultimate field
db.fighters.ensureIndex({'ultimate':1},{'unique':true})
// But, it won't work and we still need to do this. This is the case where the sparse index is needed for.
db.fighters.ensureIndex({'ultimate':1},{'unique':true, 'sparse':true})
// Now, If we want to query fighters where we want to get any documents that have indexed 'ultimate' values, we'll do query as follow:
db.fighters.find().hint({'ultimate':1})
// What if we want to query fighters that does not have ultimate values , yet , we still hint the query to look at indexed ultimate key ?
// We could attempt on doing that, but it would return no result
db.fighters.find({'ultimate': null}).hint({'ultimate':1})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment