欢迎投稿

今日深度:

MongoDB学习笔记(六) MongoDB索引用法和效率分析(1(3)

三、索引的效率

MongoDB的索引到底能不能提高查询效率呢?我们在这里通过一个例子来测试。比较同样的数据在无索引和有索引的情况下的查询速度。

首先,我们通过这样一个方法插入10W条数据:

  1. public void InsertBigData()    
  2. {    
  3.     var random = new Random();    
  4.     for (int i = 1; i < 100000; i++)    
  5.     {    
  6.         Document doc = new Document();    
  7.         doc["ID"] = i;    
  8.         doc["Data"] = "data" + random.Next(100000);    
  9.         mongoCollection.Save(doc);    
  10.     }    
  11.     Console.WriteLine("当前有" + mongoCollection.FindAll().Documents.Count() + "条数据");    
  12. }  

然后,实现一个方法用来创建索引:

  1. public void CreateIndexForData()    
  2. {    
  3.     mongoCollection.Metadata.CreateIndex(new Document { { "Data"1 } }, false);    
  4. }  

还有排序的方法:

  1. public void SortForData()    
  2. {    
  3.     mongoCollection.FindAll().Sort(new Document { { "Data"1 } });    
  4. }  

运行测试代码如下:

  1. static void Main(string[] args)    
  2. {    
  3.     IndexBLL indexBll = new IndexBLL();    
  4.     indexBll.DropAllIndex();    
  5.     indexBll.DeleteAll();    
  6.     indexBll.InsertBigData();    
  7.     Stopwatch watch1 = new Stopwatch();    
  8.     watch1.Start();    
  9.     for (int i = 0; i < 1; i++) indexBll.SortForData();    
  10.     Console.WriteLine("无索引排序执行时间:" + watch1.Elapsed);    
  11.     indexBll.CreateIndexForData();    
  12.     Stopwatch watch2 = new Stopwatch();    
  13.     watch2.Start();    
  14.     for (int i = 0; i < 1; i++) indexBll.SortForData();    
  15.     Console.WriteLine("有索引排序执行时间:" + watch2.Elapsed);    
  16. }  

最后执行程序查看结果:

多次测试表明在有索引的情况下,查询效率要高于无索引的效率。


www.htsjk.Com true http://www.htsjk.com/shujukujc/18886.html NewsArticle 三、索引的效率 MongoDB的索引到底能不能提高查询效率呢?我们在这里通过一个例子来测试。比较同样的数据在无索引和有索引的情况下的查询速度。 首先...
评论暂时关闭