Pra*_*gat 2 geolocation geospatial mongodb mongodb-query aggregation-framework
我在MongoDB中有数据表示Circle如下:
{
"_id" : ObjectId("54c1dc6506a4344d697f7675"),
"location" : [
23.027573,
72.50675800000001
],
"radius" : 500
}
Run Code Online (Sandbox Code Playgroud)
我想用lat和long查询以确定该位置是否存储了lat&long和radius.
我尝试了以下查询但无法执行:
db.test.find({location:{ $geoWithin: { $center: [ [ -74, 40.74 ] ,
"$radius"] } }})
Run Code Online (Sandbox Code Playgroud)
我们如何在geoWithin查询中使用存储的半径?
实际上比第一次写作时更优化.现在我们可以$expr而不是$match布尔和$geoNear后来:
db.collection.aggregate([
{ "$geoNear": {
"near": {
"type": "Point",
"coordinates": [ 23.027573, 72.50675800000001 ],
},
"distanceField": "distance"
}},
{ "$match": { "$expr": { "$lte": [ "$distance", "$radius" ] } }}
])
Run Code Online (Sandbox Code Playgroud)
您已经准确地存储了信息,但是获得结果的方法与您想象的不同.
您想要使用的是该运算符$redact的聚合框架形式.这是你做的:
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"
}
}}
])
Run Code Online (Sandbox Code Playgroud)
因此,该表单允许查询点的距离在结果中"投影",而查询也只返回最近的文档.
然后使用逻辑比较来查看"距离"值是否小于"半径",因此在圆圈内.
最后,您匹配以仅筛选出"内部"断言为真的结果.
您可以添加其他选项,$project如文档中所示.我还强烈建议您的存储也应该使用GeoJSON格式,因为它可能与您可能用于处理获得的结果的任何其他库更兼容.