索引是提高查询查询效率最有效的手段。索引是一种特殊的数据结构,索引以易于遍历的形式存储了数据的部分内容(如:一个特定的字段或一组字段值),索引会按一定规则对存储值进行排序,而且索引的存储位置在内存中,所在从索引中检索数据会非常快。如果没有索引,MongoDB必须扫描集合中的每一个文档,这种扫描的效率非常低,尤其是在数据量较大时。
1. 创建/重建索引
MongoDB全新创建索引使用ensureIndex()方法,对于已存在的索引可以使用reIndex()进行重建。
1.1 创建索引ensureIndex()
MongoDB创建索引使用ensureIndex()或createIndex()方法。
如,为集合sites建立索引:
db.sites.ensureIndex({
name: 1, domain: -1})
db.sites.createIndex({
"person.name":1})
1.2 重建索引reIndex()
如,重建集合sites的所有索引:
db.sites.reIndex()
2. 查看索引
MongoDB提供了查看索引信息的方法:getIndexes()方法可以用来查看集合的所有索引,totalIndexSize()查看集合索引的总大小,db.system.indexes.find()查看数据库中所有索引信息。
2.1 查看集合中的索引getIndexes()
如,查看集合sites中的索引:
db.sites.getIndexes()
查询结果格式:
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "newDB.sites"
},
{
"v" : 1,
"key" : {
"name" : 1,
"domain" : -1
},
"name" : "name_1_domain_-1",
"ns" : "newDB.sites"
}
]
2.2 查看集合中的索引大小totalIndexSize()
如,查看集合sites索引大小:
db.sites.totalIndexSize()
2.3 查看数据库中所有索引db.system.indexes.find()
如,当前数据库的所有索引:
db.system.indexes.find()
3. 删除索引
3.1 删除指定的索引dropIndex()
要先查询出需要删除的索引名称 name。
如,删除集合sites中名为"name_1_domain_1"的索引:
db.sites.dropIndex("name_1_domain_1")
3.2 删除所有索引dropIndexes()
如,删除集合sites中所有的索引:
db.sites.dropIndexes()
参考原文:https://itbilu.com/database/mongo/E1tWQz4_e.html#show-index