http:///database/mongo/E1tWQz4_e.html 索引是提高查詢查詢效率最有效的手段。索引是一種特殊的數(shù)據(jù)結(jié)構(gòu),索引以易于遍歷的形式存儲了數(shù)據(jù)的部分內(nèi)容(如:一個特定的字段或一組字段值),索引會按一定規(guī)則對存儲值進行排序,而且索引的存儲位置在內(nèi)存中,所在從索引中檢索數(shù)據(jù)會非???。如果沒有索引,MongoDB必須掃描集合中的每一個文檔,這種掃描的效率非常低,尤其是在數(shù)據(jù)量較大時。 創(chuàng)建/重建索引 查看索引 刪除索引
1. 創(chuàng)建/重建索引MongoDB全新創(chuàng)建索引使用ensureIndex() 方法,對于已存在的索引可以使用reIndex() 進行重建。 1.1 創(chuàng)建索引ensureIndex() MongoDB創(chuàng)建索引使用ensureIndex() 方法。 語法結(jié)構(gòu) db.COLLECTION_NAME.ensureIndex(keys[,options]) 如,為集合sites 建立索引: > db.sites.ensureIndex({name: 1, domain: -1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
} 注意:1.8 版本之前創(chuàng)建索引使用createIndex() ,1.8 版本之后已移除該方法 1.2 重建索引reIndex() 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
} 2. 查看索引MongoDB提供了查看索引信息的方法:getIndexes() 方法可以用來查看集合的所有索引,totalIndexSize() 查看集合索引的總大小,db.system.indexes.find() 查看數(shù)據(jù)庫中所有索引信息。 2.1 查看集合中的索引getIndexes() 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"
}
] 2.2 查看集合中的索引大小totalIndexSize() db.COLLECTION_NAME.totalIndexSize() 如,查看集合sites 索引大?。?/p> > db.sites.totalIndexSize()
16352 2.3 查看數(shù)據(jù)庫中所有索引db.system.indexes.find() db.system.indexes.find() 如,當前數(shù)據(jù)庫的所有索引: > db.system.indexes.find() 3. 刪除索引不在需要的索引,我們可以將其刪除。刪除索引時,可以刪除集合中的某一索引,可以刪除全部索引。 3.1 刪除指定的索引dropIndex() db.COLLECTION_NAME.dropIndex("INDEX-NAME") 如,刪除集合sites 中名為"name_1_domain_-1"的索引: > db.sites.dropIndex("name_1_domain_-1")
{ "nIndexesWas" : 2, "ok" : 1 } 3.3 刪除所有索引dropIndexes() db.COLLECTION_NAME.dropIndexes() 如,刪除集合sites 中所有的索引: > db.sites.dropIndexes()
{
"nIndexesWas" : 1,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
|