适用对象:
MongoDB vCore
运算符 $near
返回其位置字段接近指定点(按距离排序)的文档。 它需要“2dsphere”索引,并返回最接近到最远的文档。
语法
{
<location field>: {
$near: {
$geometry: {
type: "Point",
coordinates: [<longitude>, <latitude>]
},
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
}
参数
参数 | 类型 | DESCRIPTION |
---|---|---|
location field |
领域 | 包含 GeoJSON 点的字段 |
$geometry |
物体 | 指定中心点的 GeoJSON Point 对象 |
$maxDistance |
编号 | 可选。 距离中心点的最大距离(以米为单位) |
$minDistance |
编号 | 可选。 距离中心点的最小距离(以米为单位) |
例子
创建所需的“2dsphere”索引:
db.stores.createIndex({ "location": "2dsphere" })
示例 1:基本邻近搜索
在Proseware家庭娱乐中心位置附近查找商店(70.1272,69.7296),按距离排序:
db.stores.find({
'location': {
$near: {
$geometry: {
type: "Point",
coordinates: [69.7296, 70.1272] // [longitude, latitude]
}
}
}
}, {
name: 1,
location: 1
})
示例 2:使用最大距离
在 10 KM 的首届 Up 顾问麦克风集市内查找商店 (-112.7858, -29.1866):
db.stores.find({
'location': {
$near: {
$geometry: {
type: "Point",
coordinates: [-112.7858, -29.1866]
},
$maxDistance: 10000 // 10 kilometers in meters
}
}
}, {
name: 1,
location: 1
})
示例 3:使用最小距离和最大距离
从 Wide World Importers 查找 10 到 50 KM 之间的商店(-82.5543、-65.105):
db.stores.aggregate([
{
$geoNear: {
near: {
type: "Point",
coordinates: [-82.5543, -65.105]
},
distanceField: "distance",
minDistance: 10000, // 10 KM in meters
maxDistance: 50000, // 50 KM in meters,
spherical: true
}
},
{
$project: {
name: 1,
location: 1,
distanceKm: { $divide: ["$distance", 1000] },
_id: 0
}
}
])
这会返回与指定点之间的距离的存储,例如:
- 距离附近商店(以公里为单位)
- 仅在指定距离范围内存储
- 从最接近到最远的排序