MongoDB的索引(五)
十一、2d Indexes
1、在MongoDB 2.2版本之前或者地址位置字段没有使用GeoJSON进行存储的情况下,我们使用2d索引比较多。
2、2d索引一般是用来计算平面上的计算,对于球面的一些几何计算,或者以GeoJSON形式来进行存储的字段,需要使用2dsphere索引
3、2d索引本质上也是一个稀疏索引
4、2d索引不支持collation选项
5、创建语法
db.<collection>.createIndex( { <location field> : "2d" ,
<additional field> : <value> } ,
{ <index-specification options> } )
db.collection.createIndex( { <location field> : "2d" } ,
{ min : <lower bound> , max : <upper bound> } ) //设置最大最小边界值和精度。默认情况下,最大值和最小值的范围是[ -180 , 180 ),精度是26位的精度6、对于2d复合索引来讲,必须将2d索引字段放在复合索引最前缀
> db.places.createIndex( { state:1,"locs": "2d"} )
{
"ok" : 0,
"errmsg" : "2d has to be first in index",
"code" : 16801,
"codeName" : "Location16801"
}7、查询语法
1)查询在指定范围内所有的点 - 平面
语法:
db.<collection>.find( { <location field> :
{ $geoWithin :
{ $box|$polygon|$center : <coordinates>
} } } )示例:
查询在[ 0 , 0 ],[ 100 , 100 ]之内的所有点:
db.places.find( { loc :
{ $geoWithin :
{ $box : [ [ 0 , 0 ] ,
[ 100 , 100 ] ]
} } } )
查询以[-74, 40.74 ]为中心,10为半径的范围内所有的点:
db.places.find( { loc: { $geoWithin :
{ $center : [ [-74, 40.74 ] , 10 ]
} } } )2)查询球面中的范围查询
语法:
db.<collection>.find( { <location field> :
{ $geoWithin :
{ $centerSphere : [ [ <x>, <y> ] , <radius> ] }
} } )示例:
db.<collection>.find( { loc : { $geoWithin :
{ $centerSphere :
[ [ 88 , 30 ] , 10 / 3963.2 ]
} } } )3)查询一个平面的临近点
语法:
db.<collection>.find( { <location field> :
{ $near : [ <x> , <y> ]
} } )示例:
db.place.find( { loc :{ $near : [ 23 , 57 ]} } )4)精确匹配一个点
语法:
db.<collection>.find( { loc: [ <x> , <y> ] } )示例:
db.place.find( { loc : [ 23 , 57 ] } )十二、Hash Indexes
1、hash索引可以做分片键,这会使数据分布更加随机性
2、hash索引会通过一个hash函数来计算该文档的hash索引值,hash支持嵌套文档,但是不支持多键。
3、hash索引是由MongoDB实例来自动计算使用hash索引的,应用程序无需对其进行hash计算
4、创建hash索引语法
db.collection.createIndex( { _id: "hashed" } )5、hash索引不支持创建复合索引
6、hash索引仅支持等值查询,也可以在相同的字段创建普通索引,范围查询会优先使用普通索引,等值查询优先使用hash索引。



