正在学习MongoDB到“内嵌索引”部分,动手过程如下:
peoples = [ {"name":{"first":"joe", "last":"schome"}, "age":27}, {"name":{"first":"simon", "last":"wade"}, "age":18}, {"name":{"first":"joe", "last":"kelly"}, "age":30} ]成功插入集合:
> db.peoples.insert(peoples) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })成功创建索引:
> db.peoples.ensureIndex({"name.first":1, "age":-1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.peoples.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.peoples" }, { "v" : 1, "key" : { "name.first" : 1, "age" : -1 }, "name" : "name.first_1_age_-1", "ns" : "test.peoples" } ]查询:
> db.peoples.find().pretty() { "_id" : ObjectId("556dcd540d56f64140620b54"), "name" : { "first" : "joe", "last" : "schome" }, "age" : 27 } { "_id" : ObjectId("556dcd540d56f64140620b55"), "name" : { "first" : "simon", "last" : "wade" }, "age" : 18 } { "_id" : ObjectId("556dcd540d56f64140620b56"), "name" : { "first" : "joe", "last" : "kelly" }, "age" : 30 } >为什么创建的索引没有发生作用呢?
于是,尝试删除上面创建的索引,对age创建一个简单的索引:
> db.peoples.dropIndex("name.first_1_age_-1") { "nIndexesWas" : 2, "ok" : 1 } > db.peoples.ensureIndex({"age":-1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.peoples.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.peoples" }, { "v" : 1, "key" : { "age" : -1 }, "name" : "age_-1", "ns" : "test.peoples" } ] > db.peoples.find().pretty() { "_id" : ObjectId("556dcd540d56f64140620b54"), "name" : { "first" : "joe", "last" : "schome" }, "age" : 27 } { "_id" : ObjectId("556dcd540d56f64140620b55"), "name" : { "first" : "simon", "last" : "wade" }, "age" : 18 } { "_id" : ObjectId("556dcd540d56f64140620b56"), "name" : { "first" : "joe", "last" : "kelly" }, "age" : 30 }非内嵌文档索引一样没效果……
真是百思不得其解~
你的问题让我好奇怪,你这个find()就是查出所有的数据了,里面又没有任何条件,索引怎么可能起作用呢……而且,你紧紧通过 db.peoples.find().pretty()就想看索引有无起作用是不对的,应该是db.peoples.find().explain(),通过这个explain()来看看mongodb有无使用到索引的######
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。