本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$nearSphere
Amazon DocumentDB 中的$nearSphere运算符用于查找距离地理空间点指定距离内的文档。此运算符对于地理空间查询特别有用,例如查找给定位置一定半径范围内的所有餐厅。
参数
-
$geometry: 表示参考点的 GeoJSON 对象。必须是带有type和coordinates字段的Point对象。
-
$minDistance:(可选)文档必须位于的参考点的最小距离(以米为单位)。
-
$maxDistance:(可选)从文档必须位于的参考点的最大距离(以米为单位)。
示例(MongoDB 外壳)
在此示例中,我们将找到距离华盛顿州西雅图特定地点 2 千米(2000 米)范围内的所有餐厅。
创建示例文档
db.usarestaurants.insert([
{
name: "Noodle House",
location: { type: "Point", coordinates: [-122.3516, 47.6156] }
},
{
name: "Pike Place Grill",
location: { type: "Point", coordinates: [-122.3403, 47.6101] }
},
{
name: "Seattle Coffee Co.",
location: { type: "Point", coordinates: [-122.3339, 47.6062] }
}
]);
查询示例
db.usarestaurants.find({
location: {
$nearSphere: {
$geometry: {
type: "Point",
coordinates: [-122.3516, 47.6156]
},
$minDistance: 1,
$maxDistance: 2000
}
}
}, {
name: 1
});
输出
{ "_id" : ObjectId("611f3da985009a81ad38e74b"), "name" : "Noodle House" }
{ "_id" : ObjectId("611f3da985009a81ad38e74c"), "name" : "Pike Place Grill" }
代码示例
要查看使用该$nearSphere命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findNearbyRestaurants() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const restaurants = db.collection('usarestaurants');
const result = await restaurants.find({
location: {
$nearSphere: {
$geometry: {
type: "Point",
coordinates: [-122.3516, 47.6156]
},
$minDistance: 1,
$maxDistance: 2000
}
}
}, {
projection: { name: 1 }
}).toArray();
console.log(result);
client.close();
}
findNearbyRestaurants();
- Python
-
from pymongo import MongoClient
def find_nearby_restaurants():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
restaurants = db.usarestaurants
result = list(restaurants.find({
'location': {
'$nearSphere': {
'$geometry': {
'type': 'Point',
'coordinates': [-122.3516, 47.6156]
},
'$minDistance': 1,
'$maxDistance': 2000
}
}
}, {
'name': 1
}))
print(result)
client.close()
find_nearby_restaurants()