我在 MongoDB 中有代表一个圆的数据,如下所示:
{
"_id" : ObjectId("54c1dc6506a4344d697f7675"),
"location" : [
23.027573,
72.50675800000001
],
"radius" : 500
}
我想查询经纬度以确定位置是否在存储的经纬度和半径范围内。
我尝试了以下查询但无法执行:
db.test.find({location:{ $geoWithin: { $center: [ [ -74, 40.74 ] ,
"$radius"] } }})
我们如何在 geoWithin 查询中使用存储的半径?
最佳答案
比原来的更优化,你现在可以使用 $expr
在 $match
内初始阶段后$geoNear
:
db.collection.aggregate([
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [ 23.027573, 72.50675800000001 ],
},
"distanceField": "distance"
}},
{ "$match": { "$expr": { "$lte": [ "$distance", "$radius" ] } }}
])
实际上比第一次写的时候优化了一点。现在我们可以 $redact
而不是 $project
bool 值和 $match
后来:
db.collection.aggregate([
// Match documents "near" the queried point
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [ 23.027573, 72.50675800000001 ],
},
"distanceField": "distance"
}},
// Calculate if distance is within radius and remove if not
{ "$redact": {
"$cond": {
"if": { "$lte": [ "$distance", "$radius" ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
您已经按照应有的方式存储了信息,但是获取结果的方法与您想象的不同。
您要使用的是 $geoNear
特别是 aggregation framework该运算符的形式。以下是您的操作:
db.collection.aggregate([
// Match documents "near" the queried point
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [ 23.027573, 72.50675800000001 ],
},
"distanceField": "distance"
}},
// Calculate if distance is within radius
{ "$project": {
"location": 1,
"radius": 1,
"distance": 1,
"within": { "$lte": [ "$distance", "$radius" ] }
}},
// Match only documents within the radius
{ "$match": { "within": true } }
])
因此该表单允许在结果中“投影”到查询点的距离,同时查询也将只返回最近的文档。
然后您使用逻辑比较来查看“距离”值是否小于“半径”,因此在圆内。
最后,您进行匹配以仅过滤掉“内部”断言为真的那些结果。
您可以向 $geoNear
添加其他选项,如文档中所示。我还强烈建议您的存储也应该使用 GeoJSON 格式,因为它可能与您可能用来处理获得的结果的任何其他库更兼容。
关于mongodb - 在存储的圆圈内查找位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28104000/