语法:
db.collection.createIndex(keys, options)
单键唯一索引:db.users. createIndex({username :1},{unique:true});
单键唯一稀疏索引:db.users. createIndex({username :1},{unique:true,sparse:true});
复合唯一稀疏索引:db.users. createIndex({username:1,age:-1},{unique:true,sparse:true});
创建哈希索引并后台运行:db.users. createIndex({username :'hashed'},{background:true});
删除索引示例:
根据索引名字删除某一个指定索引:db.users.dropIndex("username_1");
删除某集合上所有索引:db.users.dropIndexs();
重建某集合上所有索引:db.users.reIndex();
查询集合上所有索引:db.users.getIndexes();
查询优化技巧:
第一步:找出慢速查询
db.orders.find({"useCode":"jack", "orderTime" :
{ "$lt" : new Date("2017-08-03T16:00:00.000Z")}}).explain('executionStats')
可以看到一共检查了1060007个文档,返回了88560个文档,执行了299ms,stage是COLLSCAN,没用索引,
按照上诉优化步骤:
1.找出慢速查询:
db.setProfilingLevel(1,100)
db.orders.find({"useCode":"jack", "orderTime" :
{ "$lt" : new Date("2017-08-03T16:00:00.000Z")}})
查看是否有超过100ms的语句:
db.system.profile.find().sort({'$natural':-1}).limit(5).pretty()
db.orders.find({"useCode":"jack", "orderTime" :
{ "$lt" : new Date("2017-08-03T16:00:00.000Z")}}).explain('executionStats')
db.orders.createIndex({"useCode":-1})
db.orders.createIndex({'useCode':1,'orderTime':1})
符合我们的优化目标(扫描文档数跟返回数是一样的),但是时间却长了,所以建索引还是要以实践为主,扫描的文档数少不一定能提高效率。
后来发现这个索引更快:
db.orders.createIndex( { useCode: 1 }, { collation: { locale: "fr" } } )
db.orders.find({"useCode":"jack", "orderTime" : { "$lt" : new Date("2017-08-03T16:00:00.000Z")}}).collation( { locale: "fr" } ).explain('executionStats')
关于此用法介绍的地址:https://docs.mongodb.com/manual/reference/command/createIndexes/index.html
关于索引的建议:
索引很有用,但是它也是有成本的——它占内存,让写入变慢;
mongoDB通常在一次查询里使用一个索引,所以多个字段的查询或者排序需要复合索引才能 更加高效;
复合索引的顺序非常重要
在生成环境构建索引往往开销很大,时间也不可以接受,在数据量庞大之前尽量进行查询优化和 构建索引;
避免昂贵的查询,使用查询分析器记录那些开销很大的查询便于问题排查;
通过减少扫描文档数量来优化查询,使用explai对开销大的查询进行分析并优化;
索引是用来查询小范围数据的,不适合使用索引的情况:
8.每次查询都需要返回大部分数据的文档,避免使用索引
9.写比读多