坐标适合一定范围的MongoDB查询对象



我有一个存储位置数量的文档。我的目标是找到特定纬度和纵向之间的所有位置。我现在的方法不是很有效。我获取所有位置并在 for 循环中过滤它们。我想使用$range方法。

locationsCollection.find({}).toArray(function(err, results){
var locations = [];
for(var key in results){
if( 
results[key].latitude > req.query.latitude - latitudeOffset &&
results[key].latitude < req.query.latitude + latitudeOffset && 
results[key].longitude > req.query.longitude - longitudeOffset && 
results[key].longitude < req.query.longitude + longitudeOffset
)
locations.push({
location: results[key].location,
latitude: results[key].latitude,
longitude: results[key].longitude
});
}
res.json({error: false, locations: locations});
});

你可以使用MongoDB的地理空间查询来做到这一点。

MongoDB允许您使用GeoJSON对象,这是使用JSON描述位置数据的标准。

例如,我有一个位置集合:

> db.test.find()
{ "_id": 0, "loc": { "type": "Point", "coordinates": [ 1, 1 ] } }
{ "_id": 1, "loc": { "type": "Point", "coordinates": [ 2, 2 ] } }
{ "_id": 2, "loc": { "type": "Point", "coordinates": [ 20, 20 ] } }

使用特殊的 2dsphere 索引:

> db.test.createIndex({loc: '2dsphere'})

然后我想找出哪些位置位于使用 GeoJSON 的多边形对象描述的特定"框"中:

> db.test.find({
loc: {
$geoWithin: {
$geometry: {
type: 'Polygon',
coordinates: [ [ [0,0], [3,6], [6,1], [0,0] ] ]
}
}
}
})

结果是:

{ "_id": 0, "loc": { "type": "Point", "coordinates": [ 1, 1 ] } }
{ "_id": 1, "loc": { "type": "Point", "coordinates": [ 2, 2 ] } }

其中,它显示坐标为[20, 20]的位置位于查询中的边界框之外。

注意:MongoDB的地理空间查询遵循地球的曲率,根据大地测量学。也就是说,在处理使用2dsphere索引的查询时,将考虑地球的曲率。大多数地图是投影到平面 2D 平面中的球体,因此在 2D 中看起来像直线的东西不会是球体中的直线。

注意:GeoJSON 的坐标系顺序为[ Longitude, Latitude ],这与典型的(纬度、经度)对相反。

最新更新