【问题标题】:MongoDB: Not getting correct result using $geoWithin operatorMongoDB:使用 $geoWithin 运算符没有得到正确的结果
【发布时间】:2023-03-15 14:58:01
【问题描述】:

我使用$geoWithin 表示圆圈,但我没有得到预期的结果。有两个集合,一个用于users,第二个用于items。我正在为项目设置半径和坐标。所以我必须在那个坐标和半径内找到一个用户。

用户收藏

{
    "_id" : NumberLong(25287),
    "_class" : "com.samepinch.domain.user.User",
    "name":"XYZ",
    "location" : [
        74.866247,
        31.63336
    ]
}

物品集合

{
    "_id" : NumberLong(46603),
    "itemName" : "Chandigarh",
    "categoryName" : "TRAVELLING",
    "location" : {
        "_id" : null,
        "longitude" : 77.15319738236303,
        "latitude" : 28.434568229025803,
        "radius" : 29153.88048637637
    }
}

根据物品坐标和用户坐标,两地之间的距离约为500公里。

查询

db.users.find({ location: { $geoWithin: { $center: [ [77.15319738236303,28.434568229025803], 29153.88048637637/3963.2] } } } ).count()

根据 $geoWithin,用户不应该显示,但它正在显示。如果我做错了什么,请帮助我。

谢谢

【问题讨论】:

    标签: mongodb geolocation geospatial spring-data-mongodb


    【解决方案1】:

    如果您以后想在项目中查询与$geoWithin$centerSphere 相关的内容,请仅指定您的字段结构,如下所示:-

    "location" : {
            "lng" : 77.15319738236303,
            "lat" : 28.434568229025803
        },
    "redius" : 120

    然后进行如下查询:-

    db.collection.find( {location: { $geoWithin: { $centerSphere: [ [ lat, lng ], radius/3963.2] } }} )

    【讨论】:

      【解决方案2】:

      我认为您的问题是,您搜索的范围太广了。 根据MongoDB documentation$centerSphere的正确语法是:

      db.<name>.find( {
          loc: { $geoWithin: 
           { 
              $centerSphere: [ [ <longitude>, <latitude> ],
              <radius in MILES>/3963.2 ] } 
           }
      } )
      

      您现在正在搜索点周围 29153.88048637637 英里半径内的点,并且两个点都在您定义的中心周围的半径内。

      希望对你有帮助:)

      【讨论】:

      • 如果我想在太宽的范围内搜索该怎么办?
      • 您正在搜索点周围约 29.153 英里 = 约 46.917 公里的半径范围内。由于地球的半径只有 6.371 公里,从逻辑上讲,地球上的每个点都会满足您的$geoWithin 条件。您应该考虑缩小半径。
      【解决方案3】:

      只是因为我现在已经遇到过几次了,所以我想详细说明一下 Ashutosh 的答案。

      半径必须以弧度为单位,并且转换基于您希望使用的单位的球体半径。假设您使用地球作为您的球体并且您希望您的$geoWithin 以米为单位,那么您可以将radius 字段设置为meters/(6371*1000),或者您想要的距离除以地球的半径距离代表的单位。

      这个列表应该会有所帮助:

      • 米:meters/6371000 为单位的距离(以米为单位的地球平均半径)
      • 公里:km/6371 中的距离
      • 英里:miles/3959 中的距离
      • 英尺:feet/20903520 中的距离

      【讨论】:

        猜你喜欢
        • 2021-10-12
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-08
        • 2014-11-16
        • 1970-01-01
        相关资源
        最近更新 更多