Javascript MongoDB查询坐标在一定范围内的对象

Javascript MongoDB查询坐标在一定范围内的对象,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我有一个文档,其中存储了许多位置。我的目标是找到在一定纬度和经度之间的所有位置。目前我的方法不是很有效。我得到所有的位置,并在一个for循环中过滤它们。我想使用$range方法 locationsCollection.find({}).toArray(function(err, results){ var locations = []; for(var key in results){ if( results[key].latitude

我有一个文档,其中存储了许多位置。我的目标是找到在一定纬度和经度之间的所有位置。目前我的方法不是很有效。我得到所有的位置,并在一个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});
});
locationsCollection.find({}).toArray(函数(err,results){
var位置=[];
用于(var输入结果){
如果(
结果[key].latitude>req.query.latitude-latitudeOffset&&
结果[key]。纬度req.query.longitude-longitudeOffset&&
结果[键]。经度
您可以使用MongoDB的

MongoDB允许您使用,这是使用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 ] } }
特别报告员:

然后,我想找到特定“框”内的位置,使用以下描述:

结果是:

{ "_id": 0, "loc": { "type": "Point", "coordinates": [ 1, 1 ] } }
{ "_id": 1, "loc": { "type": "Point", "coordinates": [ 2, 2 ] } }
其中显示坐标为
[20,20]
的位置位于查询中的边界框之外

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


注意: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 ] } }