使用$ near和2d指数的Mongo地理定位不准确

ddi*_*ase 1 geolocation geospatial mongoose mongodb

我编写了一个应用程序来查找本地机构并通过RESTful API提供它们.我的堆栈是:express,express-resource和mongoose.这是我的模型示例:

var PlaceSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            required: true
        },
        geolocation: {
            lat: Number,
            lng: Number
        },
        address: {
            type: String
        }
    }
);
PlaceSchema.index({
    geolocation: '2d'
});
Run Code Online (Sandbox Code Playgroud)

我已经检查了几次,我的lon/lat值正确存储在db中,所以没有任何数据错误.

然后我运行查询以获取具有特定查询值的数据:

mongoose.connection.db.executeDbCommand(
    {
        geoNear: 'places',
        near: [
            parseFloat(req.body.lat),
            parseFloat(req.body.lng)
        ],
        num: limit,
        query: {
            // Some additional queries that
            // don't impact the geo results.
        },
        spherical: true,
        distanceMultiplier: 6371, // converting results to km
        maxDistance: distance / 6371,
    },
    function(err, result)
    {
        res.send(200, {
            status: true,
            data:   theaters
        });
    }
);
Run Code Online (Sandbox Code Playgroud)

它返回的结果存在一些问题:a)以km为单位的计算确实是错误的.在大多数情况下,有6-7公里的差异,但它会有所不同,b)距离较近的地方看起来比其他地方更远.

我正在使用直接mongoose查询,因​​为它将返回计算的距离(我的API返回所需的距离).切换到mongoose find方法显然不会让我获得对这些数据的访问权限.

想知道我的索引是否错了?它应该是2dsphere吗?这方面的文档有点令人困惑,但我看到的大多数例子只使用了2d.

谢谢你!

Asy*_*sky 9

无论您在MongoDB中使用何种类型的地理空间索引,您始终必须先存储经度,然后再存储纬度.

来自http://docs.mongodb.org/manual/core/2d/#store-points-on-a-2d-plane和文档中的其他多个位置:

无论是作为数组还是文档,如果使用经度和纬度,请按以下顺序存储坐标:经度,纬度.