MongoDB:使用$ geoWithin运算符无法获得正确的结果

问题描述 投票:0回答:3

我使用$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
3个回答
1
投票

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

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

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

我希望这可以帮助你 :)


2
投票

如果您希望以后在项目中查询与$geoWithin$centerSphere相关的信息,请仅指定您的字段结构: -

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

然后查询如下: -

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

0
投票

只是因为我现在遇到过这几次,我想详细说明Ashutosh的回答。

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

此列表应该有所帮助:

  • 米:meters/6371000的距离(地球的平均半径,以米为单位)
  • 公里:km/6371的距离
  • 英里:miles/3959的距离
  • 脚:feet/20903520的距离
© www.soinside.com 2019 - 2024. All rights reserved.