今天簡單分享一下MongoDB使用過程中的一些性能優化,其實並不只適用MongoDB,其他數據庫多少也可適用。
首先先隨機導入一千萬條數據。這里我分段導入的,因為mongo的BsonDocument一次導入的數據有限制,之前有一次最多導入20w左右,當然那次的對象字段要多很多,
所以本次測試每次導入為10w。咻咻咻咻咻咻咻咻咻咻的一聲就導完了。
/// <summary> /// 批量導入 /// </summary> public void ImportBatch() { string[] nameArr = { "周", "吳", "鄭", "王" }; string[] addressArr = { "浙江省杭州市", "浙江杭州", "浙江省杭州市濱江區", "北京", "上海", "廣州", "深圳" }; int[] ageArr = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; int[] sexArr = { 0, 1 }; //總條數一千萬條 int count = 10000000; //每次導入 int size = 100000; //分num次導入 var num = (int)Math.Ceiling((double)count / (double)size); for (int i = 0; i < num; i++) { //最后一批導入 List<BsonDocument> docs = new List<BsonDocument>(); for (int j = i * size; j < (i + 1) * size; j++) { var user = new User() { Name = GetStrRandomNumber(nameArr) + j, Age = GetIntRandomNumber(ageArr), Address = GetStrRandomNumber(addressArr), Sex = GetIntRandomNumber(sexArr), }; var json = JsonHelper.SerializeObject(user); BsonDocument document = BsonDocument.Parse(json); docs.Add(document); } //導入mongodb mongoServer.ImportBatch(collName, docs); } } /// <summary> /// 隨機獲取int數組的值 /// </summary> /// <param name="a"></param> /// <returns></returns> static int GetIntRandomNumber(int[] a) { Random rnd = new Random(); int index = rnd.Next(a.Length); return a[index]; } /// <summary> /// 隨機獲取string數組的值 /// </summary> /// <param name="a"></param> /// <returns></returns> static string GetStrRandomNumber(string[] a) { Random rnd = new Random(); int index = rnd.Next(a.Length); return a[index]; } /// <summary> /// 批量導入 /// </summary> /// <param name="collectionName"></param> /// <param name="docs"></param> public void ImportBatch(string collectionName, List<BsonDocument> docs) { var collection = database.GetCollection<BsonDocument>(collectionName); collection.InsertMany(docs); }
然后進行測試,先去看下索引db.getCollection('users').AgetIndexes(),可以看到主鍵_id是索引
然后隨便找一條數據測試。
可以看到用主鍵_id(0.002s)性能比Name(5.638)明顯快很多。然后給Name建立個索引,然后再用Name(0.042)做搜索條件。
再測試下Age字段,用Age倒序排,取前100條。
建立索引之后。db.getCollection('users').ensureIndex({"Age":-1})
上面主要測試索引的效率。當然要避免"$nin",模糊查詢等一系列全文檔掃描的查詢條件,會很影響效率
如果就要通過地址字段模糊查詢,那樣也可以根據地址進行分庫,分表的處理,可以根據數據量大熱門城市建立user_beijing,user_shanghai,user_hangzhou等處理方案。
具體就不多說了。
紙上得來終覺淺,絕知此事要躬行。