本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$near
Amazon DocumentDB 中的$near运算符用于查找地理位置靠近指定点的文档。它返回按距离排序的文档,最接近的文档排在最前面。此运算符需要 2dsphere 地理空间索引,可用于位置数据的邻近查询。
参数
-
$geometry: 一个 GeoJSON 点对象,用于定义近距离查询的中心点。 -
$maxDistance:(可选)文档与查询相匹配的最大距离(以米为单位)。 -
$minDistance:(可选)文档与查询相匹配的最小距离(以米为单位)。
索引要求
-
2dsphere index:对 GeoJSON 点数据进行地理空间查询所必需的。
示例(MongoDB 外壳)
以下示例演示如何使用$near运算符查找距离华盛顿州西雅图特定地点最近的餐厅。
创建示例文档
db.usarestaurants.insert([ { "name": "Noodle House", "city": "Seattle", "state": "Washington", "rating": 4.8, "location": { "type": "Point", "coordinates": [-122.3517, 47.6159] } }, { "name": "Pike Place Grill", "city": "Seattle", "state": "Washington", "rating": 4.2, "location": { "type": "Point", "coordinates": [-122.3403, 47.6062] } }, { "name": "Lola", "city": "Seattle", "state": "Washington", "rating": 4.5, "location": { "type": "Point", "coordinates": [-122.3407, 47.6107] } } ]);
创建 2dsphere 索引
db.usarestaurants.createIndex({ "location": "2dsphere" });
使用 geoJSON 点查询示例
db.usarestaurants.find({ location: { $near: { $geometry: { type: "Point", coordinates: [-122.3516, 47.6156] }, $maxDistance: 100, $minDistance: 10 } } });
输出
{
"_id" : ObjectId("69031ec9ea1c2922a1ce5f4a"),
"name" : "Noodle House",
"city" : "Seattle",
"state" : "Washington",
"rating" : 4.8,
"location" : {
"type" : "Point",
"coordinates" : [ -122.3517, 47.6159 ]
}
}
代码示例
要查看使用该$near命令的代码示例,请选择要使用的语言的选项卡: