该 $geometry
运算符指定地理空间查询的 GeoJSON 几何对象。 它用于其他地理空间运算符来定义空间计算的形状和点。
{
$geometry: {
type: <GeoJSON type>,
coordinates: <coordinates>
}
}
参数 | DESCRIPTION |
---|---|
type |
GeoJSON 对象类型(Point、Polygon、MultiPolygon 等) |
coordinates |
将 GeoJSON 对象定义为数组的坐标 |
为了获得更好的性能,请先创建所需的 2dsphere 索引。
db.stores.createIndex({ "location": "2dsphere" })
此查询最多检索两个最接近点的存储点 [46.2917, -62.6354],按邻近度排序。
它使用 $near 运算符按距离特定点对结果进行排序,帮助查找地理位置最接近给定位置的存储。
db.stores.find({
'location': {
$near: {
$geometry: {
type: "Point",
coordinates: [46.2917, -62.6354]
}
}
}
}, {
name: 1,
location: 1
}).limit(2)
该查询返回提供的坐标周围的两个最近的存储。
{
"_id": "59c355e9-586c-44f8-bbaf-a87989142119",
"name": "Relecloud | Outdoor Furniture Shop - Chetside",
"location": { "lat": 46.188, "lon": -62.2789 }
},
{
"_id": "d3a9cc23-e6ae-4806-93ac-1ade2f624742",
"name": "VanArsdel, Ltd. | Furniture Place - North Dustinside",
"location": { "lat": 47.3426, "lon": -62.4031 }
}
此查询最多找到两个存储区,这些存储的位置与由 [-80.0, -75.0] 到 [-55.0, -70.0] 的坐标边界的已定义的矩形多边形相交。
$geoIntersects
操作员查找与多边形边界重叠或触摸的存储 - 非常适合用于识别与特定地理区域交互的位置,无论是完全位于其中还是只是越过边缘。
db.stores.find({
'location': {
$geoIntersects: {
$geometry: {
type: "Polygon",
coordinates: [[
[-80.0, -75.0], // Bottom-left
[-80.0, -70.0], // Top-left
[-55.0, -70.0], // Top-right
[-55.0, -75.0], // Bottom-right
[-80.0, -75.0] // Close polygon
]]
}
}
}
}, {
"name": 1,
"location": 1,
"city": 1
}).limit(2)
此查询查找其坐标与定义的多边形边界重叠的存储。
{
"_id": "6bba7117-d180-4584-b50c-a2f843e9c9ab",
"name": "Wide World Importers | Craft Supply Mart - Heaneybury",
"location": { "lat": -64.4843, "lon": -107.7003 },
"city": "Heaneybury"
},
{
"_id": "2fd37663-e0ff-41d0-9c5a-3aec86285daa",
"name": "Relecloud | Cleaning Supply Closet - Patiencehaven",
"location": { "lat": -70.6077, "lon": -105.9901 },
"city": "Patiencehaven"
}
该示例最多检索两个存储区的位置位于两个定义的矩形区域(MultiPolygon):一个位于坐标 [120.0, -13.0] 附近的 [125.0, -10.0] 和另一个靠近 [44.0, -64.0] 到 [48.0, -61.0]。
它使用具有 MultiPolygon 几何图形的 $geoWithin 运算符搜索由任何指定多边形括起来的存储区,使其可用于同时跨多个非相邻地理区域进行查询。
db.stores.find({
'location': {
$geoWithin: {
$geometry: {
type: "MultiPolygon",
coordinates: [
[[
[120.0, -13.0],
[120.0, -10.0],
[125.0, -10.0],
[125.0, -13.0],
[120.0, -13.0]
]],
[[
[44.0, -64.0],
[44.0, -61.0],
[48.0, -61.0],
[48.0, -64.0],
[44.0, -64.0]
]]
]
}
}
}
}, {
name: 1,
location: 1
}).limit(2)
该查询返回位于两个定义的矩形区域中的两个存储区之一。
{
"_id": "6d70de9c-7b83-426d-81aa-f2173f97b64d",
"name": "Fabrikam, Inc. | Footwear Haven - Port Erling",
"location": { "lat": 45.641, "lon": -118.4963 }
},
{
"_id": "96d48224-ce10-4a61-999a-8536d442f81a",
"name": "Wide World Importers | Eyewear Bazaar - West Oletachester",
"location": { "lat": 47.3461, "lon": -61.6605 }
}