使用centerSphere获取最接近的数据 - MongoDB

时间:2012-08-07 13:16:08

标签: mongodb

我正在尝试从以下数据中获取最接近的数据

> db.points.insert({name:"Skoda" , pos : { lon : 30, lat : 30 } }) 
> db.points.insert({name:"Honda" , pos : { lon : -10, lat : -20 } }) 
> db.points.insert({name:"Skode" , pos : { lon : 10, lat : -20 } }) 
> db.points.insert({name:"Skoda" , pos : { lon : 60, lat : -10 } }) 
> db.points.insert({name:"Honda" , pos : { lon : 410, lat : 20 } }) 

> db.points.ensureIndex({ loc : "2d" })

然后我试了

> db.points.find({"loc" : {"$within" : {"$centerSphere" : [[0 , 0],5]}}})

这次我得到了不同的错误

error: {
    "$err" : "Spherical MaxDistance > PI. Are you sure you are using radians?",
    "code" : 13461

然后我试了

> db.points.find({"loc" : {"$within" : {"$centerSphere" : [[10 , 10],2]}}})
error: {
    "$err" : "Spherical distance would require wrapping, which isn't implemented yet",
    "code" : 13462

如何完成这项工作?我只想根据GEO点的给定辐射得到最接近的数据。

由于

2 个答案:

答案 0 :(得分:2)

有几点需要注意。首先,您将坐标存储在名为“pos”的字段中,但您正在对名为“loc”的字段进行查询(并创建了索引)。

$ centerSphere采用一组坐标和一个以弧度表示的值。所以$ centerSphere:[[10,10],2]在2 *(地球半径)= 12,756 km的圆圈中搜索[10,10]周围的项目。 $ centerSphere运算符不是为了在这么大的区域中搜索文档而设计的(绕地球两极缠绕是很棘手的)。尝试使用较小的值,例如.005。

最后,将坐标作为元素存储在数组中可能是一个更好的主意,因为某些驱动程序可能无法保留文档中字段的顺序(并且交换纬度和经度会导致完全不同的地理位置)。

答案 1 :(得分:0)

希望这会有所帮助:

地球半径约为3963.192英里或6378.137公里。

1英里:

db.places.find( { loc: { $centerSphere: [ [ -74, 40.74 ] ,
                                    1 / 3963.192 ] } } )