Last active
August 29, 2015 14:02
-
-
Save saintc0d3r/1d552cf965c3d7e1c797 to your computer and use it in GitHub Desktop.
Multi keys index in MongoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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