MongoDB - 使用$ centerSphere坐标输入的字段值? [子查询相当于?]

时间:2014-11-28 00:42:27

标签: mongodb mongodb-query geospatial database nosql

获得了地点及其相应坐标的数据库。 我希望得到一个特定地方附近的所有地方,而centerSphere也能做到这一点。

问题是我只能通过硬编码long / lat坐标来实现这一点,而不是像子查询结果那样使用。 我在哪里查询知道特定ID的地方的长/纬度值,如:

db.places.find(
   {_id: '9'},
   {_id:0, coordinates:1}
)

并获得一组坐标,如:

[-20.32, 89.02]


现在它起作用了:

{ $geoWithin:
    {$centerSphere: [ [ -20.32, 89.02 ] , 100 / 3960 ] }
}

我正在寻找更像的东西:

X = db.places.find(    {_id: '9'},       {_id:0, coordinates:1} )
{ $geoWithin:
    {$centerSphere: [ X , 100 / 3960 ] }
}

[不是字面意思,只是认为^^是表达我想要做的最明确的方式]

1 个答案:

答案 0 :(得分:0)

好像你想在_id已知的地方附近获取'地点'(但是lat,lon不是)

一个简单的选择是两步查找。我会findOne(),因为您使用_id作为查询

result = db.places.findOne( {_id: '9'}, {_id:0, coordinates:1} )
lonlat = result.coordinates

db.places.find( { $geoWithin:
    {$centerSphere: [ lonlat , 100 / 3960 ] }
})

第二个选项是自定义map-reduce aggregation。我对这些聚合没有经验,但想象它很简单。

mongo的聚合管道非常棒,通过管道运行聚合并使用临时变量传递'coordinates'的值会很好。

db.places.aggregate( [{ $match: {"_id" : 9}} , 
{ $project: { "lonlat":  "$coordinates"}} , 
{ $geoNear: { near : { coordinates: "$lonlat"}, 
maxDistance: 1000, spherical: true, distanceField: "dist.calculated", } }])

但是$ geoNear必须是聚合的第一阶段。并且您的案例需要_id的匹配阶段;所以不可能。此外,您的坐标似乎不是2dsphere geojson格式。

更新--- 请注意,可以在shell中使用javascript,包括变量(var)。

var result = db.places.findOne( {_id: '9'}, {_id:0, coordinates:1} );
print(result);
printjson(result);
printjson(result[0]);