MongoDB geoNear命令结果中的距离以千米为单位。

4

我使用MongoDB来存储GPS位置数据,格式为GeoJSON文档:

{"type" : "Point", "coordinates" : [33.313183, 44.465632]}

{"type" : "Point", "coordinates" : [33.2926487, 44.4159651]}

更新:我还保证了2dsphere索引如下:

db.test.ensureIndex( { loc : "2dsphere" } )

我从Google地图得到了坐标。现在,如果我使用这个命令进行搜索,我无法将结果中的距离转换为公里。

db.runCommand({geoNear: 'test', spherical: true, near: {type: "Point" , coordinates: [33.2926487, 44.4159651]}})

结果如下:
"results" : [
    {
        "dis" : 0.0033427770982422957,
        "obj" : {
            "_id" : ObjectId("54a96f348fa05fcaed637a22"),
            "loc" : {
                "type" : "Point",
                "coordinates" : [
                    33.2926487,
                    44.4159651
                ]
            }
        }
    },
    {
        "dis" : 5764.7060911604085,
        "obj" : {
            "_id" : ObjectId("54a96f4c8fa05fcaed637a23"),
            "loc" : {
                "type" : "Point",
                "coordinates" : [
                    33.313183,
                    44.465632
                ]
            }
        }
    }
]

第一个结果预期为零,因为它与源坐标和目标坐标相同,但仍有值。

我无法将第二个值转换为公里,在谷歌距离计算器中约为5.26公里。

4个回答

11
在继续研究这个问题时,我发现有两种类型的点存储方式。
传统点的格式如下:
db.test2.insert({location: [33.313183, 44.465632]})

并且GeoJSON点的格式如下

db.test.insert({location: {"type" : "Point", "coordinates" : [33.313183, 44.465632]}})

如果我们使用传统的坐标点,结果将为弧度,因此我们将使用以下语句将其转换为千米

db.runCommand({geoNear: 'test2', spherical: true, near: [33.2926487, 44.4159651], distanceMultiplier: 6371})
如果我们使用 GeoJSON point,结果将会以米为单位,因此我们将使用这个语句将其转换为千米,作为对这个问题的答案。
db.runCommand({geoNear: 'test', spherical: true, near: {type: "Point" , coordinates: [33.2926487, 44.4159651]}, distanceMultiplier: 0.001})

如果使用GeoJSON点格式,请参考此解决方案

要了解更多详细信息,请查看此链接,这是一份针对MongoDB的错误报告,其中解释了所有内容。


7

距离以米为单位返回。要转换为千米,请除以1000。您可以使用distanceMultiplier选项让MongoDB执行此操作:

db.runCommand({ "geoNear" : "test", "spherical" : true, "distanceMultiplier" : 0.001, "near" : { "type" : "Point" , "coordinates" : [33.2926487, 44.4159651] } })

这似乎是最接近实际距离的答案,但在geoNear文档中提到距离以弧度为单位,如果我想转换,应该乘以地球半径。你觉得呢? - Shweelan Leon Sam
1
这里不是弧度。地球上两点间的距离在弧度上永远不会超过2* pi。当使用传统坐标对时,将返回弧度。 - wdberkeley

0

你是否将该字段索引为2dsphere?这可能解释了差异,因为你正在查询sphere: true


是的,我已经使用以下命令添加了2dsphere索引:db.test.ensureIndex( { loc : "2dsphere" } ) - Shweelan Leon Sam

0

我遇到了同样的问题,但似乎很多人都忽略了使用geoNear时关于坐标设置的重要点。

当使用传统坐标时,geoNear命令和$geoNear聚合操作符都是以弧度为单位运作;而当使用GeoJSON点时,则以米为单位。

https://www.mongodb.com/docs/v3.0/tutorial/geospatial-tutorial/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接