【问题标题】:Mongodb find near users point with distanceMongodb找到距离较近的用户点
【发布时间】:2017-10-05 00:13:52
【问题描述】:

我们在 mongodb 数据库中查找距离较近的用户点时遇到问题。我们的主要问题是我们不能聚合近点和距离。我们在下面的查询中使用了 $geoWithin:

db.users.find({ location: { $geoWithin: { $centerSphere: [ [ 51.410608, 35.744042 ], 2/6378.1 ] } } }).sort({"user.lastActivity":-1}).limit(100)

此查询在 0.005 秒内从 500204 条记录中返回 100 条记录。

我们还使用 $nearSphere 进行以下查询:

db.users.find({ location: { $nearSphere: { $geometry: { type: "Point", 坐标:[ 51.410608, 35.744042 ] },$maxDistance:2000 } } }).sort({"user.lastActivity":-1}).limit(100)

此查询在 8.486 秒内从 500204 条记录中返回 100 条记录。

我们还将 geoNear 用于以下查询:

db.runCommand( { geoNear: "用户", 附近:{类型:“点”,坐标:[51.410608, 35.744042]}, 球形:真, “限制”:100,“最大距离”:2000 })

此查询在 6.215 秒内从 500204 条记录中返回 100 条记录。此查询查找距离较近的点,但执行需要很长时间。

我们在 users.locations 字段上添加索引 2dsphere。

1) 请告诉我为什么$nearSphere 的执行时间比$nearSphere 多? 2) 如何使用 $nearSphere 找到近点并计算返回记录距离? 3)如何用更少的时间执行geoNear?

我们还在 1394018 条记录上找到了 mysql 的近点。执行时间为 0.0011。这次真是太棒了。

选择 st_distance_sphere(fld_geom, point(35.744042,51.410608)) 为 到 testgeom 的距离,其中 st_distance_sphere(fld_geom, point( 35.744042,51.410608))

我觉得mysql spatial比mongodb spatial很强大。

【问题讨论】:

    标签: mongodb gis 2dsphere


    【解决方案1】:

    为了提高性能,为正在搜索的字段上的集合创建一个二维球体索引。

    https://docs.mongodb.com/manual/core/2dsphere/#create-a-2dsphere-index

    还有其他类型的地理空间索引。这应该会以内存利用率为代价显着提高性能。

    【讨论】:

    • 谢谢。我们将添加 2dsphere 索引,但问题没有解决。性能不好。
    • 然后考虑将不相关的数据保存在不同的集合中,或者查看您的服务器规格。
    • 感谢您的解决方案。我们可以在 mysql 上运行这部分,但我们不能这样做。 mysql这个操作性能确实不错。
    • <your query>.explain()获取查询的执行计划,看看发生了什么
    【解决方案2】:

    $nearSphere 为您提供按距离排序的结果,而 $getWithin 没有。 我不认为 sql 查询按距离对文档进行排序(只是像 $geoWithin 一样过滤它们)

    • 对带有 $nearSphere 的 user.lastActivity 使用排序没有意义 - 您只需覆盖 $nearSphere 的距离排序。

    来自documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 2012-11-20
      • 2021-12-14
      • 2014-06-16
      • 2023-03-19
      相关资源
      最近更新 更多