Indexes
Insert some test data into db.
> db.students.insert( { name : "rado" , teachers: [0,1]} ) > db.students.insert( { name : "adam" , teachers: [0,1,3]} ) > db.students.find() { "_id" : ObjectId("52c186421fdaf7a8e42b43b8"), "name" : "rado", "teachers" : [ 0, 1 ] } { "_id" : ObjectId("52c186531fdaf7a8e42b43b9"), "name" : "adam", "teachers" : [ 0, 1, 3 ] }
That way you create an index on the array attribute.
> db.students.ensureIndex( { teachers:1 } ) > db.system.indexes.find() { "v" : 1, "key" : { "teachers" : 1 }, "ns" : "school.students", "name" : "teachers_1" }
The usage of the index should be transparent when using the find method but you can always she the execution plan.
> db.students.find() { "_id" : ObjectId("52c186421fdaf7a8e42b43b8"), "name" : "rado", "teachers" : [ 0, 1 ] } { "_id" : ObjectId("52c186531fdaf7a8e42b43b9"), "name" : "adam", "teachers" : [ 0, 1, 3 ] } { "_id" : ObjectId("52c187621fdaf7a8e42b43bb"), "name" : "jon", "teachers" : [ 2, 3 ] } > > db.students.find( { teachers : { $all : [0,1]} } ) { "_id" : ObjectId("52c186421fdaf7a8e42b43b8"), "name" : "rado", "teachers" : [ 0, 1 ] } { "_id" : ObjectId("52c186531fdaf7a8e42b43b9"), "name" : "adam", "teachers" : [ 0, 1, 3 ] } > db.students.find( { teachers : { $all : [0,1]} } ).explain() { "cursor" : "BtreeCursor teachers_1", ------ this proves that we use the index "isMultiKey" : true, "n" : 2, "nscannedObjects" : 2, "nscanned" : 2, "nscannedObjectsAllPlans" : 2, "nscannedAllPlans" : 2, "scanAndOrder" : false, "indexOnly" : false, "nYields" : 0, "nChunkSkips" : 0, "millis" : 11, "indexBounds" : { "teachers" : [ [ 0, 0 ] ] }, "server" : "mongo2:27017" }
No comments:
Post a Comment