索引简介
索引通常能够极大的提高查询效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录,这种扫描全集合的查询效率时非常低的,特别在处理大量的数据时。索引是特殊的数据结构,索引存储在一个易于便利读取的数据集合中,索引是对数据库中一列或多列的值进行排序的一种结构
建立索引后,MongoDB会额外存储一份按字段生序或降序排列的索引数据,索引结构通常采用类似btree的结构持久化存储,以保证从索引里快速(O(logN)的时间复杂度)找出某个值对应的位置信息,然后根据位置信息就能读出对应的文档。简单的说,索引就是将文档按照一个或多个字段顺序组织起来,以便能根据该字段进行高效的查询
索引限制
- 集合中索引不能超过64个
- 索引名的长度不能超过128个字符
- 一个复合索引最多可以有31个字段
索引管理
-
创建索引
- db.users.createIndex()
- db.users.ensureIndex()
options
- background: 是否在后台创建索引,默认值是false
- unique: 是否是唯一索引,默认值为false
- name: 索引的名字
- sparse: 对文档中不存在的字段数据不启用索引,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档,默认值为false
> db.users.ensureIndex({"name": 1}) // 1 代表升序,-1代表降序 { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.users.createIndex({"age": -1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 } > db.users.ensureIndex({"birth": -1}, {"background": true, "unique": false}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 3, "numIndexesAfter" : 4, "ok" : 1 }
-
查询所有索引
> db.users.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.users" }, { "v" : 2, "key" : { "name" : 1 }, "name" : "name_1", "ns" : "test.users" }, { "v" : 2, "key" : { "age" : -1 }, "name" : "age_-1", "ns" : "test.users" }, { "v" : 2, "key" : { "birth" : -1 }, "name" : "birth_-1", "ns" : "test.users", "background" : true } ]
-
查询集合中哪些字段有索引
> db.users.getIndexKeys() [ { "_id" : 1 }, { "name" : 1 }, { "age" : -1 }, { "birth" : -1 } ]
-
索引占用空间查询
> db.users.totalIndexSize(0) // 0或不传参数代表所有索引总和 81920 > db.users.totalIndexSize(1) // 传参数分别统计限制 _id_ 20480 name_1 20480 age_-1 20480 birth_-1 20480 81920
-
删除索引
> db.users.dropIndex("birth_-1") { "nIndexesWas" : 4, "ok" : 1 } > db.users.dropIndexes() // 删除集合中全部索引,不会删除主键索引
-
重建索引
> db.users.reIndex() // 重建集合中所有索引,字段和排序规则不变 { "nIndexesWas" : 3, "nIndexes" : 3, "indexes" : [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.users" }, { "v" : 2, "key" : { "name" : 1 }, "name" : "name_1", "ns" : "test.users" }, { "v" : 2, "key" : { "age" : -1 }, "name" : "age_-1", "ns" : "test.users" } ], "ok" : 1 }