MongoDB全新建立索引使用ensureIndex()
方法,对于已存在的索引能够使用reIndex()
进行重建。数据库
ensureIndex()
MongoDB建立索引使用ensureIndex()
方法。dom
语法结构工具
db.COLLECTION_NAME.ensureIndex(keys[,options])
keys
,要创建索引的参数列表。如:{KEY:1}
,其中key
表示字段名,1
表示升序排序,也可以使用使用数字-1
降序。options
,可选参数,表示创建索引的设置。可选值以下:
background
,Boolean,在后台创建索引,以便创建索引时不阻止其余数据库活动。默认值 false。unique
,Boolean,建立惟一索引。默认值 false。name
,String,指定索引的名称。若是未指定,MongoDB会生成一个索引字段的名称和排序顺序串联。dropDups
,Boolean,建立惟一索引时,若是出现重复删除后续出现的相同索引,只保留第一个。sparse
,Boolean,对文档中不存在的字段数据不启用索引。默认值是 false。v
,index version,索引的版本号。weights
,document,索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其余索引字段的得分权重。如,为集合sites
创建索引:spa
> db.sites.ensureIndex({name: 1, domain: -1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
注意:1.8
版本以前建立索引使用createIndex()
,1.8
版本以后已移除该方法.net
reIndex()
db.COLLECTION_NAME.reIndex()
如,重建集合sites
的全部索引:code
> db.sites.reIndex()
{
"nIndexesWas" : 2,
"nIndexes" : 2,
"indexes" : [
{
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "newDB.sites"
},
{
"key" : {
"name" : 1,
"domain" : -1
},
"name" : "name_1_domain_-1",
"ns" : "newDB.sites"
}
],
"ok" : 1
}
1.3 建立惟一索引blog
db.COLLECTION_NAME.ensureIndex({',},{'unique',true})
检查数据惟一性。排序
MongoDB提供了查看索引信息的方法:getIndexes()
方法能够用来查看集合的全部索引,totalIndexSize()
查看集合索引的总大小,db.system.indexes.find()
查看数据库中全部索引信息。索引
getIndexes()
db.COLLECTION_NAME.getIndexes()
如,查看集合sites
中的索引:ci
>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"
}
]
totalIndexSize()
db.COLLECTION_NAME.totalIndexSize()
如,查看集合sites
索引大小:
> db.sites.totalIndexSize()
16352
db.system.indexes.find()
db.system.indexes.find()
如,当前数据库的全部索引:
> db.system.indexes.find()
不在须要的索引,咱们能够将其删除。删除索引时,能够删除集合中的某一索引,能够删除所有索引。
dropIndex()
db.COLLECTION_NAME.dropIndex("INDEX-NAME")
如,删除集合sites
中名为"name_1_domain_-1"的索引:
> db.sites.dropIndex("name_1_domain_-1")
{ "nIndexesWas" : 2, "ok" : 1 }
dropIndexes()
db.COLLECTION_NAME.dropIndexes()
如,删除集合sites
中全部的索引:
> db.sites.dropIndexes()
{
"nIndexesWas" : 1,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
db.COLLECTION_NAME.find().explain()
可分析查询使用的索引状况,耗时,及扫描文档数的统计