文章目录
-
1. 开始与准备数据
-
2. 创建索引前
-
3. 创建索引 createIndex
-
4. 创建索引后
-
5. 删除索引
-
6.唯一索引与符合索引
-
- ①唯一索引
-
②复合索引
=================================================================================
启动mongo并选择目标数据库
mongo
use test
然后准备一组数据(10万条数据,较大的数据量)
for(i=0;i<100000;i++){db.test.insert({name:‘test’+i,age:i})}
===============================================================================
查询一下name为"test90000"的数据。并使用explain方法来查看查询的性能。
db.test1.find({name:“test90000”}).explain(‘executionStats’)
这里可以看到查询花了53毫秒
==========================================================================================
给字段name创建索引
db.test1.createIndex({name: 1})
查看索引:
给name创建索引之前,_id字段默认为索引,创建后集合有两个索引,“_id"和"name”。
===============================================================================
再次查找该条数据,并查看查询的性能,发现所用时间接近0毫秒。即设定索引后查询性能大大提升了。
db.test1.find({name:“test90000”}).explain(‘executionStats’)
==============================================================================
db.test1.dropIndex({name:1})
查看之
db.test1.getIndexes()
如图,只剩下了"_id"一个索引。"name"索引已被删除。
=================================================================================
db.test1.createIndex({name: 1},{“unique”:true})
查看索引
db.test1.getIndexes()