mongodb - 在存储的圆圈内查找位置

标签 mongodb geolocation geospatial mongodb-query aggregation-framework

我在 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/

相关文章:

json - 我如何获得在 Twitter 上发布的四方签到的位置(纬度、经度)?

mongodb - 通过聚合中的索引投影嵌套数组字段值

django - 操作失败: database error: not authorized for query on database.系统.命名空间

google-maps - 无需 GPS 即可获取位置(纬度/经度),就像我的谷歌地图位置功能一样

android - 我如何在android中获取相机 View 区域的纬度和经度以及相机 View 的用户方向

javascript - Mapbox GL JS 更新图像叠加源

node.js - Mongoose 字符串到 ObjectID

arrays - 如何在mongodb查询中通过数值查找数组的对象属性(字符串)?

postgresql - 哪里可以找到空间关系函数的源代码?

mysql - 插入空间数据时获取空列