一、数据类型定义
- 在mongodb中,空间数据以geojson和坐标对的形式保存
- Geojson数据中有两个field组成,一个是type 用来定义geojson对象类型,一个是坐标对用来定义
- 经度需在[-180,180],纬度需在[-90,90]之间
- Type定义:<field>: { type: <GeoJSON type> , coordinates: <coordinates> }
location: {
type: "Point",
coordinates: [-73.856077, 40.848447]
}
- 坐标对定义:(1)通过数组<field>: [<longitude>, <latitude> ](2)嵌入文档<field>: { <field1>: <longitude>, <field2>: <latitude> }
二、地理查询
1.建立空间索引 2dsphere:db.collection.createIndex( { <location field> : "2dsphere" } ) 此处的location field 可以使geojson或者是坐标对
2.空间索引不能用于碎片关键词
3.sharded collections碎片集合查询时,$near和$nearSpher不能使用,可以用geoNear和$geoNear代替
4.
Operation | Spherical/Flat Query | Notes |
$near (GeoJSON centroid point in this line and the following line, 2dsphere index) | Spherical | See also the $nearSphere operator, which provides the same functionality when used with GeoJSON and a 2dsphere index. |
$near (legacy coordinates, 2d index) | Flat |
|
$nearSphere (GeoJSON point, 2dsphere index) | Spherical | Provides the same functionality as $nearoperation that uses GeoJSON point and a2dsphere index. For spherical queries, it may be preferable to use$nearSphere which explicitly specifies the spherical queries in the name rather than $near operator. |
$nearSphere (legacy coordinates, 2d index) | Spherical | Use GeoJSON points instead. |
$geoWithin : { $geometry: … } | Spherical |
|
$geoWithin : { $box: … } | Flat |
|
$geoWithin : { $polygon: … } | Flat |
|
$geoWithin : { $center: … } | Flat |
|
$geoWithin : { $centerSphere: … } | Spherical |
|
Spherical |
| |
Spherical |
| |
Flat |
| |
Spherical |
| |
Flat |
|
Example
Create a collection places with the following documents:
copy
copied
db.places.insert( {
name: "Central Park",
location: { type: "Point", coordinates: [ -73.97, 40.77 ] },
category: "Parks"
} );
db.places.insert( {
name: "Sara D. Roosevelt Park",
location: { type: "Point", coordinates: [ -73.9928, 40.7193 ] },
category: "Parks"
} );
db.places.insert( {
name: "Polo Grounds",
location: { type: "Point", coordinates: [ -73.9375, 40.8303 ] },
category: "Stadiums"
} );
The following operation creates a 2dsphere index on the location field:
copy
copied
db.places.createIndex( { location: "2dsphere" } )
The following query uses the $near operator to return documents that are at least 1000 meters from and at most 5000 meters from the specified GeoJSON point, sorted in order from nearest to farthest:
copy
copied
db.places.find(
{
location:
{ $near:
{
$geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
$minDistance: 1000,
$maxDistance: 5000
}
}
}
)
The following operation uses the geoNear command to return documents that match the query filter {category: "Parks" }, sorted in order of nearest to farthest to the specified GeoJSON point:
copy
copied
db.runCommand(
{
geoNear: "places",
near: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
spherical: true,
query: { category: "Parks" }
}
)
最后求关注,求点赞,欢迎大家关注我的公众号
记录所学所用,包括但不限于遥感、地信、气象、生态环境,机器学习知识,相关文献阅读,编程代码实现。偶尔荒腔走板的聊聊其他。欢迎不同领域的朋友们加入进来,多多交流。