Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Last active August 29, 2015 14:02
Show Gist options
  • Save saintc0d3r/1d552cf965c3d7e1c797 to your computer and use it in GitHub Desktop.
Save saintc0d3r/1d552cf965c3d7e1c797 to your computer and use it in GitHub Desktop.
Multi keys index in MongoDB
// Prepare sample data on the Teachers collection
db.teachers.insert({'_id': 0, 'name': 'Maria'})
db.teachers.insert({'_id': 1, 'name': 'Jill'})
db.teachers.insert({'_id': 2, 'name': 'Anna'})
db.teachers.insert({'_id': 3, 'name': 'Lara'})
// Prepare sample data on the Students collection
db.students.insert({'_id':0, 'name':'Lisa', 'teachers': [0,1]})
db.students.insert({'_id':1, 'name':'Paulene', 'teachers': [0,1,3]})
db.students.insert({'_id':2, 'name':'Joey', 'teachers': [1,2,3]})
db.students.insert({'_id':3, 'name':'Sarah', 'teachers': [0,3]})
// Setup multi key index on the students-teachers property
db.students.ensureIndex({'teachers':1})
// Query students that are the pupils of both Lisa & Paulene
db.students.find({'teachers':{$all: [0,1]}})
// To see the statistic of the prior query, add explain after the find command
db.students.find({'teachers':{$all: [0,1]}}).explain()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment