索引的目的是为了提升查询速度,mongodb中也支持索引。
mongodb的shell同时又是js的编译器,所以我们可以用JavaScript语句模拟存入大量数据。
为了验证索引的快速,我们先模拟插入十万条数据
for(i=0;i<100000;i++)
{
db.stu.insert({name:’test’+i,age:i});
}

创建索引

db.集合.ensureIndex({“属性”:1})
1表示升序,-1,表示降序

expalin进行查询性能分析

db.stu.find({name:”test20000”}).explain(“executionStats”)
mongodb创建索引
executionStats下的executionTimeMills表示整体查询时间,单位毫秒

创建索引后
db.stu.ensureIndex({“name”:1})
在执行性能分析
db.stu.find({name:”test20000”}).explain(“executionStats”)
mongodb创建索引
时间由原来的806毫秒,减少到了3毫秒,是不是提升了很多。

索引命令

创建索引
db.stu.ensureIndex({“name”:1})

创建唯一索引
db.stu.ensureIndex({“name”:1},{“unique”:true})

联合索引,按照find()出现顺序
db.stu.ensureIndex({“name”:1},{age:1:})

查看文档索引
db.stu.getIndexes()

删除索引

db.stu.dropIndexes(‘索引名称’)

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2019-02-12
  • 2022-12-23
  • 2021-04-23
  • 2021-09-21
猜你喜欢
  • 2021-11-05
  • 2021-07-18
  • 2022-12-23
  • 2021-05-27
  • 2022-12-23
  • 2021-08-10
  • 2021-08-28
相关资源
相似解决方案