即使已创建索引,$geoNear查询仍无法找到索引。

3

我有以下架构,其中我在地理坐标上拥有一个2D索引。

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var LocationSchema = new Schema ({
    geo: {
        type: [Number],
        required: true,
        index: "2dsphere"
    }
});

module.exports = mongoose.model("Location", LocationSchema);

我想要寻找新的位置:
Location.find({
    geo: {
        $nearSphere: [req.query.lat, req.query.lng],
        $maxDistance: maxDistance
    }
}, function(err, events) {
    if (err) {
        console.log(err);
        res.status(500).json(err);
    }
    res.status(200).json(events);
});

索引似乎已经被创建:
> db.system.indexes.find();
{ "v" : 1, "key" : { "geo" : "2dsphere" }, "name" : "geo_2dsphere", "ns" : "dev.events", "background" : true, "safe" : null, "2dsphereIndexVersion" : 2 }

虽然我在这里创建了一个索引,但是当我想找到附近的位置时,出现了以下错误:

{ [MongoError: Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0
Tree: GEONEAR  field=loc maxdist=0.156961 isNearSphere=0
Sort: {}
Proj: {}
planner returned error: unable to find index for $geoNear query]
name: 'MongoError',
message: 'Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0\nTree: GEONEAR  field=loc maxdist=0.156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
'$err': 'Unable to execute query: error processing query: ns=dev.locations limit=1000 skip=0\nTree: GEONEAR  field=loc maxdist=0.156961 isNearSphere=0\nSort: {}\nProj: {}\n planner returned error: unable to find index for $geoNear query',
code: 17007 }
4个回答

7

来自Mongo Docs,Mongo使用[经度,纬度],但是在这里,您正在使用反向。


2

我在将解析数据库迁移到AWS后遇到了类似的问题。 我通过以下方式解决了该问题:

db.prod.createIndex({ "location": "2d" })

prod是我的集合名称,location是存储地理位置(GeoPoint)的列名。

有关 &geoNear 的讨论可以在geo location issue(github)找到。


0

您在位置模式中定义了“geo”,并且正在使用它进行查找

loc : {
         $nearSphere: [req.query.lat, req.query.lng],
         $maxDistance: maxDistance
      }

将其更改为

geo : {
         $nearSphere: [req.query.lat, req.query.lng],
         $maxDistance: maxDistance
      }

嗨,这不是问题所在。仍然出现相同的错误。 - user2500558
你需要根据 MongoDB 查询的格式先提供经度,然后是纬度:$nearSphere: [req.query.lng, req.query.lat]。希望这能够正常工作。 - sankar muniyappa

0

请确保查询中的字段名称与模式中的名称匹配。我遇到这个错误是因为我的模式中有“loc”,而查询却在寻找“lastLocation”。

 var mongoQuery = User.find({
                lastLocation: {
                    $near: coordinates,
                    $maxDistance: maxDistance
                }
            }).limit(limit);

var UserSchema   = new mongoose.Schema({
    //...
    lastLocation: {
        type: [Number],
        index: '2d'
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接