MongoDB: 使用 $geoWithin 运算符没有得到正确的结果

MongoDB: Not getting correct result using $geoWithin operator

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

用户collection

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

项目collection

{
    "_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 documentation$centerSphere的正确语法是:

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

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

希望对您有所帮助:)

如果你将来想在你的项目中查询与$geoWithin$centerSphere相关的内容,那么只需要像这样指定你的字段结构:-

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

然后像这样查询:-

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

只是因为我现在已经 运行 参与了几次,所以我想详细说明 Ashutosh 的回答。

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

此列表应该有所帮助:

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