場景:
在最近的項目中,用到了Mongodb,用它來保存大量工業數據。同時是會根據用戶自動建立對應的數據表。這要求同時建立索引來加快查詢。
解決:
1.在Nuget包中查詢“mongocsharpdriver”,進行安裝,這個安裝包不同於MongoDB.Driver,這個包包括了MongoDB.Driver、MongoDB.Bson等。同時可以對數據庫中每個表進行更加細致的操作,比如index,cursor等。而MongoDB.Driver只能滿足一般的增刪改查。
2.添加如下代碼:
1 public void AddIndex(string collection) 2 { 3 MongoDatabase mongoDatabase = _mongoClient.GetServer().GetDatabase(_databaseSettings.DatabaseName); 4 var datacollection = mongoDatabase.GetCollection(collection); 5 var allindex = datacollection.GetIndexes(); 6 7 if (!datacollection.IndexExistsByName("bTime_-1_eTime_-1_devId_1")) 8 { 9 var as_index = new IndexKeysBuilder().Descending("bTime"); 10 as_index.Descending("eTime"); 11 as_index.Ascending("devId"); 12 datacollection.CreateIndex(as_index); 13 } 14 16 }
3.這里的 Descending() 和 Ascending() 可以選擇字段添加升序還是降序索引,最后通過createIndex來添加索引。
4.用Navicat查看數據庫下的索引情況:
成功生成了索引。
5.最后用查詢語句測試一下,有沒有命中索引,主要用explain()語句,查看是否命中:
可以看到執行一個查詢后,inputStage中的indexName是設置的索引。