Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$minDistance
$minDistance是与$nearSphere或$geoNear结合使用的查找运算符,用于筛选距离中心点至少达到指定最小距离的文档。该运算符在 Amazon DocumentDB 中受支持,其功能与 MongoDB 中的对应运算符类似。
参数
示例(MongoDB 外壳)
在此示例中,我们将找到华盛顿州西雅图特定地点 2 公里半径范围内的所有餐厅。
创建示例文档
db.usarestaurants.insertMany([
{
"state": "Washington",
"city": "Seattle",
"name": "Noodle House",
"rating": 4.8,
"location": {
"type": "Point",
"coordinates": [-122.3517, 47.6159]
}
},
{
"state": "Washington",
"city": "Seattle",
"name": "Pike Place Grill",
"rating": 4.5,
"location": {
"type": "Point",
"coordinates": [-122.3412, 47.6102]
}
},
{
"state": "Washington",
"city": "Bellevue",
"name": "The Burger Joint",
"rating": 4.2,
"location": {
"type": "Point",
"coordinates": [-122.2007, 47.6105]
}
}
]);
查询示例
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" }
代码示例
要查看使用该$minDistance命令的代码示例,请选择要使用的语言的选项卡:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findRestaurantsNearby() {
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 collection = db.collection('usarestaurants');
const result = await collection.find({
"location": {
"$nearSphere": {
"$geometry": {
"type": "Point",
"coordinates": [-122.3516, 47.6156]
},
"$minDistance": 1,
"$maxDistance": 2000
}
}
}, {
"projection": { "name": 1 }
}).toArray();
console.log(result);
client.close();
}
findRestaurantsNearby();
- Python
-
from pymongo import MongoClient
def find_restaurants_nearby():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
collection = db.usarestaurants
result = list(collection.find({
"location": {
"$nearSphere": {
"$geometry": {
"type": "Point",
"coordinates": [-122.3516, 47.6156]
},
"$minDistance": 1,
"$maxDistance": 2000
}
}
}, {
"projection": {"name": 1}
}))
print(result)
client.close()
find_restaurants_nearby()