MongoDB 索引類似關聯式資料庫,提升查詢與排序效率,實現原理一致。因鍵可為一般型別或子文件,支援各類鍵建立索引。
_id_集合建立時自動在 _id 建立唯一索引 _id_,不可刪除。查看方式:
var _idIndex = mongoCollection.Metadata.Indexes.Single(x => x.Key == "_id_");
Console.WriteLine(_idIndex);
於單一鍵建立,1 為升序,-1 為降序:
mongoCollection.Metadata.CreateIndex(new Document { { "UserName", 1 } }, false);
查看:
var idx = mongoCollection.Metadata.Indexes.Single(x => x.Key == "_UserName_");
Console.WriteLine(idx);
多鍵組合,順序影響查詢匹配:
mongoCollection.Metadata.CreateIndex(new Document { { "UserId", 1 }, { "UserName", -1 } }, false);
針對文件型別鍵:
// 子文件整體索引
mongoCollection.Metadata.CreateIndex(new Document { { "Detail", 1 } }, false);
// 子文件內部欄位複合索引
mongoCollection.Metadata.CreateIndex(new Document { { "Detail.Address", 1 }, { "Detail.Age", -1 } }, false);
第三參數設 true。注意:缺失鍵視為 null,亦受唯一限制,建議確保鍵值存在。
mongoCollection.Metadata.CreateIndex(new Document { { "UserId", 1 } }, true);
foreach (var index in mongoCollection.Metadata.Indexes)
Console.WriteLine(index.Value);
輸出範例:
{ "name": "_id_", "ns": "myDatabase.UserInfo", "key": { "_id": 1 } }
{ "name": "_UserId_unique_", "ns": "myDatabase.UserInfo", "key": { "UserId": 1 }, "unique": true, ... }
{ "name": "_UserName_", "ns": "myDatabase.UserInfo", "key": { "UserName": 1 }, "unique": false, ... }
{ "name": "_Detail.Address_Detail.Age_", "ns": "myDatabase.UserInfo", "key": { "Detail.Address": 1, "Detail.Age": -1 }, ... }
索引資訊含:name、ns(所屬庫.集合)、key(欄位與排序)、unique、_id 等。
誤區:以為刪除集合即刪除索引。MongoDB 中集合資料清空索引仍在,需手動刪除。
// 刪除指定索引
mongoCollection.Metadata.DropIndex("_UserName_");
// 批量刪除除 _id_ 外所有索引
public void DropAllIndex()
{
var list = mongoCollection.Metadata.Indexes.ToList();
for (int i = 0; i < list.Count; i++)
if (list[i].Key != "_id_")
mongoCollection.Metadata.DropIndex(list[i].Key);
}
插入 10 萬筆測試資料,對比無索引與有索引排序耗時:
public void InsertBigData()
{
var random = new Random();
for (int i = 1; i < 100000; i++)
{
var doc = new Document { { "ID", i }, { "Data", "data" + random.Next(100000) } };
mongoCollection.Save(doc);
}
Console.WriteLine("當前有 " + mongoCollection.FindAll().Documents.Count() + " 條資料");
}
public void CreateIndexForData()
{
mongoCollection.Metadata.CreateIndex(new Document { { "Data", 1 } }, false);
}
public void SortForData()
{
mongoCollection.FindAll().Sort(new Document { { "Data", 1 } });
}
// 測試主程式
static void Main(string[] args)
{
IndexBLL bll = new IndexBLL();
bll.DropAllIndex(); bll.DeleteAll(); bll.InsertBigData();
var w1 = Stopwatch.StartNew();
bll.SortForData();
Console.WriteLine("無索引排序耗時:" + w1.Elapsed);
bll.CreateIndexForData();
var w2 = Stopwatch.StartNew();
bll.SortForData();
Console.WriteLine("有索引排序耗時:" + w2.Elapsed);
}
實測將直觀展現索引對排序查詢的巨大加速效果。