http://itbilu.com/database/mongo/E1tWQz4_e.html
索引是提高查询查询效率最有效的手段。索引是一种特殊的数据结构,索引以易于遍历的形式存储了数据的部分内容(如:一个特定的字段或一组字段值),索引会按一定规则对存储值进行排序,而且索引的存储位置在内存中,所在从索引中检索数据会非常快。如果没有索引,MongoDB必须扫描集合中的每一个文档,这种扫描的效率非常低,尤其是在数据量较大时。
MongoDB全新创建索引使用ensureIndex()方法,对于已存在的索引可以使用reIndex()进行重建。
MongoDB创建索引使用ensureIndex()方法。
语法结构
db.COLLECTION_NAME.ensureIndex(keys[,options])
我们可以为内嵌文档创建索引,其规则和普通文档没有任何差别,如: db.test.ensureIndex({"comments.date":1})
如,为集合sites建立索引:
> db.sites.ensureIndex({name: 1, domain: -1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
注意:1.8版本之前创建索引使用createIndex(),1.8版本之后已移除该方法
db.COLLECTION_NAME.reIndex()
如,重建集合sites的所有索引:
> 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
}
MongoDB提供了查看索引信息的方法:getIndexes()方法可以用来查看集合的所有索引,totalIndexSize()查看集合索引的总大小,db.system.indexes.find()查看数据库中所有索引信息。
db.COLLECTION_NAME.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"
}
]
db.COLLECTION_NAME.totalIndexSize()
如,查看集合sites索引大小:
> db.sites.totalIndexSize()
16352
db.system.indexes.find()
如,当前数据库的所有索引:
> db.system.indexes.find()
不在需要的索引,我们可以将其删除。删除索引时,可以删除集合中的某一索引,可以删除全部索引。
db.COLLECTION_NAME.dropIndex("INDEX-NAME")
如,删除集合sites中名为"name_1_domain_-1"的索引:
> db.sites.dropIndex("name_1_domain_-1")
{ "nIndexesWas" : 2, "ok" : 1 }
db.COLLECTION_NAME.dropIndexes()
如,删除集合sites中所有的索引:
> db.sites.dropIndexes()
{
"nIndexesWas" : 1,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
背景描述
300G 的数据创建索引,执行 db.collection.ensureIndex({key:1}) 之后,打开另一个终端,任何操作都不能执行。
根本原因
在数据库建立索引时,默认时 “foreground” 也就是前台建立索引,但是,当你的数据库数据量很大时,在建立索引的时会读取数据文件,大量的文件读写会阻止其他的操作,命令没有显性指定 background,所以命令会锁库。
解决方案
执行 db.collection.ensureIndex({key:1},{background: true}),这样就不会锁库了,建立索引就会在后台处理了。(注:“{key:1}” 中,1 表示升序 - asc,-1 表示降序 - desc )
在后台建立索引的时候,不能对建立索引的 collection 进行一些坏灭型的操作,如:运行 repairDatabase,drop,compat,当你在建立索引的时候运行这些操作的会报错。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:http://blog.itpub.net/29096438/viewspace-2153604/