1.索引详解
1.1 添加索引
//为number 创建索引
db.orderInfo.ensureIndex({totalAmount:1})
//执行结果
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1.0
}
1.2 指定索引名称
//指定索引名称
db.orderInfo.ensureIndex({insert_time:-1},{name:"idx_insertTime"})
//执行结果
/* 1 */
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1.0
}
1.3 唯一索引
db.orderInfo.ensureIndex({orderNo:-1},{unique:true})
//执行结果
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 4,
"numIndexesAfter" : 5,
"ok" : 1.0
}
//唯一索引之前已经有重复数值如何处理
db.orderInfo.ensureIndex({orderNo:-1},{unique:true,dropDups:true})
1.4 强制使用索引
//指定索引必须是已经创建了的索引
db.orderInfo.find({orderNo:"11111",number:1}).hint({orderNo:-1})
1.5 查询执行计划
db.orderInfo.find({orderNo:"123456"}).explain()
//执行计划解释
“cursor” : “BtreeCursor name_-1“ 使用索引
“nscanned” : 1 查到几个文档
“millis” : 0 查询时间0是很不错的性能
1.7 查询索引
db.getCollection('orderInfo').getIndexes()
//查询结果
/* 1 */
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "afdata.orderInfo"
},
{
"v" : 2,
"key" : {
"totalAmount" : 1.0
},
"name" : "totalAmount_1",
"ns" : "afdata.orderInfo"
},
{
"v" : 2,
"key" : {
"insert_time" : -1.0
},
"name" : "idx_insertTime",
"ns" : "afdata.orderInfo"
}
]
1.8 查询系统索引
db.system.indexes.find()
db.system.namespaces.find()
1.9 后台执行索引
//为了不影响查询我们可以叫索引的创建过程在后台
db.orderInfo.ensureIndex({orderNo:-1},{background:true})
1.10 删除索引
//指定删除索引
db.runCommand({dropIndexes : "orderInfo" , index:"name_-1"})
//删除collection全部索引
db.runCommand({dropIndexes : "orderInfo" , index:""})
2 索引使用注意
- 创建索引的时候注意1是正序创建索引-1是倒序创建索引
- 索引的创建在提高查询性能的同事会影响插入的性能,对于经常查询少插入的文档可以考虑用索引
- 符合索引要注意索引的先后顺序
- 每个键全建立索引不一定就能提高性能呢,索引不是万能的
- 在做排序工作的时候如果是超大数据量也可以考虑加上索引,用来提高排序的性能
3.空间索引
3.1. 添加2D索引
db.map.ensureIndex({"gis":"2d"},{min:-1,max:201})
默认会建立一个[-180,180]之间的2D索引
查询点(70,180)最近的3个点
db.map.find({"gis":{$near:[70,180]}},{gis:1,_id:0}).limit(3)
3.2.查询
3.2.1 查询1
以点(50,50)和点(190,190)为对角线的正方形中的所有的点
db.map.find({gis:{"$within":{$box:[[50,50],[190,190]]}}},{_id:0,gis:1})
3.2.2 查询2
查询出以圆心为(56,80)半径为50规则下的圆心面积中的点
db.map.find({gis:{$within:{$center:[[56,80],50]}}},{_id:0,gis:1})