Mongodb資料庫的索引操作很簡單,隻需要把作為條件的字段設定為索引即可
> use user
switched to db user
> show collections
system.indexes
u_info
u_setting
> db.system.indexes.find(); 這是預設的索引(預設為_id為索引)
{ "name" : "_id_", "ns" : "user.u_info", "key" : { "_id" : ObjectId("000000000000000000000000") } }
{ "name" : "_id_", "ns" : "user.u_setting", "key" : { "_id" : ObjectId("000000000000000000000000") } }
>
> db.u_info.insert({uid:1,name:"Falcon.C",address:"Beijing"});
> db.u_info.insert({uid:2,name:"sexMan",address:"Wuhan"});
> db.u_info.find();
{ "_id" : ObjectId("4b9cf280c84d7f20576c4df2"), "uid" : 1, "name" : "Falcon.C", "address" : "Beijing" }
{ "_id" : ObjectId("4b9cf284c84d7f20576c4df3"), "uid" : 2, "name" : "sexMan", "address" : "Wuhan" }
插入了2條記錄,我們來把uid設定為索引字段:
> db.u_info.ensureIndex({uid:1});
> db.u_info.ensureIndex({name:1});
> db.system.indexes.find();
{ "ns" : "user.u_info", "key" : { "uid" : 1 }, "name" : "uid_1" }
{ "ns" : "user.u_info", "key" : { "name" : 1 }, "name" : "name_1" }
>
這時我們看到多了剛才我們設定的那個字段,這樣在查詢的時候,如果查詢條件有uid字段或name字段,則走索引來進行查詢
有索引:
> db.u_info.find({name:"Falcon.C"});
> db.u_info.find({name:"Falcon.C"}).explain();
{
"cursor" : "BtreeCursor name_1",
"startKey" : {
"name" : "Falcon.C"
},
"endKey" : {
"nscanned" : 1,
"n" : 1,
"millis" : 0,
"allPlans" : [
{
"cursor" : "BtreeCursor name_1",
"startKey" : {
"name" : "Falcon.C"
},
"endKey" : {
}
}
]
}
删除索引後:
> db.system.indexes.find();
> db.u_info.dropIndex("name_1")
{ "nIndexesWas" : 3, "ok" : 1 }
"cursor" : "BasicCursor",
"nscanned" : 2,
"cursor" : "BasicCursor",
通過以上可以看出,查詢的條件中有索引時,查詢走BtreeCursor 的索引,而沒有索引時走BasicCursor
通常需要索引的字段是:
1.唯一鍵 _id 是預設被設定為索引的
2.需要被查找的字段應該建立索引,比如在find()裡面的字段
3.需要被排序的字段應該建立索引。比如在sort()裡面的字段
以上就是MongoDB
的索引操作
本文轉自 不得閑 部落格園部落格,原文連結: http://www.cnblogs.com/DxSoft/archive/2010/10/21/1857364.html ,如需轉載請自行聯系原作者