现在可以使用 Azure DocumentDB 存储和查询地理空间数据。 此增强功能提供了强大的工具来管理和分析空间数据,从而支持各种应用程序,例如实时位置跟踪、路由优化和空间分析。
下面是现在支持的地理空间命令和运算符的快速概述:
地理空间查询运算符
$geoIntersects
选择指定几何图形与文档几何图形相交的文档。 用于查找与给定几何图形共享任何空间部分的文档。
db.collection.find({
location: {
$geoIntersects: {
$geometry: {
type: "<GeoJSON object type>",
coordinates: [[[...], [...], [...], [...]]]
}
}
}
})
$geoWithin
选择具有完全存在于指定形状内的地理空间数据的文档。 此运算符用于查找定义区域中的文档。
db.collection.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[[...], [...], [...], [...]]]
}
}
}
})
$box
使用两个坐标对(左下角和右上角)定义矩形区域。 用于 $geoWithin 运算符查找此矩形中的文档。 例如,在地图上查找矩形区域内的所有位置。
db.collection.find({
location: {
$geoWithin: {
$box: [[lowerLeftLong, lowerLeftLat], [upperRightLong, upperRightLat]]
}
}
})
$center
使用中心点和弧度半径定义圆形区域。 用于 $geoWithin 运算符查找此圆圈中的文档。
db.collection.find({
location: {
$geoWithin: {
$center: [[longitude, latitude], radius]
}
}
})
$centerSphere
类似于 $center,但使用中心点和半径(以弧度为单位)定义球面区域。 适用于球面几何计算。
db.collection.find({
location: {
$geoWithin: {
$centerSphere: [[longitude, latitude], radius]
}
}
})
$geometry
指定要定义几何图形的 GeoJSON 对象。 与地理空间运算符一起使用,根据复杂形状执行查询。
db.collection.find({
location: {
$geoIntersects: {
$geometry: {
type: "<GeoJSON object type>",
coordinates: [longitude, latitude]
}
}
}
})
$maxDistance
指定与地理空间查询的点之间的最大距离。 与运算符一$near起使用$nearSphere。 例如,在给定点的 2 公里内查找所有位置。
db.collection.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: distance
}
}
})
$minDistance
指定与地理空间查询的点之间的最小距离。 与运算符一$near起使用$nearSphere。
db.collection.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$minDistance: distance
}
}
})
$polygon
使用坐标对数组定义多边形。 用于 $geoWithin 运算符查找此多边形中的文档。
db.collection.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[[...], [...], [...], [...]]]
}
}
}
})
$near
查找靠近指定点的文档。 返回按距离点排序的文档。 例如,查找用户位置最近的餐馆。
db.collection.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: distance
}
}
})
$nearSphere
类似于 $near,但在球面上执行计算。 对地球表面更准确的距离计算非常有用。
db.collection.find({
location: {
$nearSphere: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: distance
}
}
})
地理空间聚合阶段
$geoNear
执行地理空间查询以返回按距离指定点排序的文档。 可以包含其他查询条件和返回距离信息。
db.collection.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [longitude, latitude]
},
distanceField: "distance",
spherical: true
}
}
])
注意事项和不支持的功能
目前,不支持使用单环 GeoJSON 多边形进行查询,该多边形的区域超过单个半球。 在这种情况下,Azure DocumentDB 返回以下错误消息:
Error: Custom CRS for big polygon is not supported yet.不允许使用常规索引和地理空间索引的复合索引。 例如:
db.collection.createIndex({a: "2d", b: 1}); Error: Compound 2d indexes are not supported yet目前不支持带孔的多边形用于$geoWithin查询。 尽管插入带有孔的多边形不受限制,但它最终会失败并显示以下错误消息:
Error: $geoWithin currently doesn't support polygons with holes$geoNear聚合阶段始终需要键字段。 如果缺少键字段,则会发生以下错误:
Error: $geoNear requires a 'key' option as a String和
$geoNear$near$nearSphere阶段没有严格的索引要求,因此,如果缺少索引,这些查询不会失败。