适用对象:
MongoDB vCore
运算符 $geoWithin
选择其位置字段完全位于指定几何图形中的文档。 此运算符支持各种形状运算符,包括$box
、$polygon
$center
和$geometry
。
语法
运算符的 $geoWithin
语法因所使用的形状而异:
// Using $box
{
<location field>: {
$geoWithin: {
$box: [ [ <bottom left coordinates> ], [ <upper right coordinates> ] ]
}
}
}
// Using $center
{
<location field>: {
$geoWithin: {
$center: [ [ <x>, <y> ], <radius> ]
}
}
}
// Using $geometry
{
<location field>: {
$geoWithin: {
$geometry: {
type: <GeoJSON type>,
coordinates: <coordinates>
}
}
}
}
参数
参数 | 类型 | DESCRIPTION |
---|---|---|
location field |
领域 | 包含位置坐标的字段 |
$box |
数组 | 定义框对面角的两组坐标 |
$center |
数组 | 中心点坐标和半径(以度为单位) |
$geometry |
物体 | 定义边界的 GeoJSON 对象 |
例子
首先,请确保具有 2dsphere 索引:
db.stores.createIndex({ "location": "2dsphere" })
示例 1:使用$box
在家庭娱乐商店周围的矩形区域内查找商店:
db.stores.find({
'location': {
$geoWithin: {
$box: [
[65.0, 65.0], // Bottom left corner
[75.0, 75.0] // Top right corner
]
}
}
}, {
name: 1,
location: 1
})
此查询将返回存储,包括“Proseware, Inc. |家庭娱乐中心“(位于70.1272,69.7296)。
示例 2:使用 $center
在 Wide World Importers 的圆形半径内查找商店:
db.stores.find({
'location': {
$geoWithin: {
$center: [
[-82.5543, -65.105], // Center point (Wide World Importers location)
5 // Radius in degrees
]
}
}
}, {
name: 1,
location: 1
})
示例 3:使用 $geometry
查找多边形区域中的存储:
db.stores.find({
'location': {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[
[-85.0, -70.0],
[-85.0, -60.0],
[-75.0, -60.0],
[-75.0, -70.0],
[-85.0, -70.0]
]]
}
}
}
}, {
name: 1,
location: 1
})
更全面地分析结果:
db.stores.aggregate([
{
$match: {
'location': {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[
[-85.0, -70.0],
[-85.0, -60.0],
[-75.0, -60.0],
[-75.0, -70.0],
[-85.0, -70.0]
]]
}
}
}
}
},
{
$project: {
name: 1,
location: 1,
_id: 0
}
}
])