MongoDB'无法找到$ geoNear查询的索引'

fra*_*nkV 38 geospatial mongodb mongodb-query

我只是想让一个简单的near查询工作.这是我的文档样本.

{"point": 
  {"type": "Point", 
     "coordinates": [30.443902444762696, -84.27326978424058]}, 
   "created_on": {"$date": 1398016710168}, 
   "radius": 180, 
   "user": {"$oid": "53543188eebc5c0cc416b77c"}, 
   "_id": {"$oid": "53544306eebc5c0ecac6cfba"}, 
   "expires_on": {"$date": 1399831110168}
}
Run Code Online (Sandbox Code Playgroud)

和mongod我尝试了命令:

db.bar.find({point: {$near: [-84.26060492426588, 30.45023887165371]}});
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

错误:{"$ err":"无法执行查询:错误处理查询:ns = foo.bar skip = 0 \nTree:GEONEAR field = point maxdist = 1.79769e + 308 isNearSphere = 0 || First:notFirst:full path :point \nSort:{} \nProj:{} \n planner返回错误:无法找到$ geoNear查询的索引","代码":17007}

也许我的谷歌今天不是那么尖锐,但我找不到任何东西.另外,我运行了ensure index命令.我的意图是这些是地图位置.

db.bar.ensureIndex({a:1});
db.bar.ensureIndex({geo:"2d"});
Run Code Online (Sandbox Code Playgroud)

dav*_*veh 71

几个问题,你在foo数据库的foo集合上创建了索引,但是正在查询bar集合.你需要在正确的集合上.

读取已插入的文档需要添加"2dsphere"索引以支持geoJson对象.这个索引需要在你文档的"point"元素上,所以试试吧

db.bar.createIndex({point:"2dsphere"});
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过为查询提供geoJson obj来进行以下查询:

db.bar.find(
   { point :
       { $near :
          {
            $geometry : {
               type : "Point" ,
               coordinates : [-84.27326978424058, 30.443902444762696] },
            $maxDistance : 1
          }
       }
    }
)
Run Code Online (Sandbox Code Playgroud)

  • 很好,使用以下方法解决了我的问题:`db.<collection> .ensureIndex({point:"2dsphere"});` (6认同)

Kri*_*m R 10

db.prod.createIndex({ "location": "2d" })
Run Code Online (Sandbox Code Playgroud)

这为我解决了同样的问题.

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

关于这一点的一些讨论可以在这里找到


Nei*_*unn 7

因此,这里似乎有些错误:

  • 根据您显示的数据以及查询信息,相关信息包含在字段点下并以GeoJSON格式包含。您的索引创建:
db.foo.createIndex({geo:“ 2d”})

不会“失败”,因为目前没有名为“ geo”的字段,并且包含数据的字段应该在该位置。如果改为使用“ point”(这是正确的字段),那么您将收到一条错误消息,告知您该类型的索引对GeoJSON数据无效。您需要一个“ 2dsphere”索引:

db.points.createIndex({ "point": "2dsphere" })
Run Code Online (Sandbox Code Playgroud)
  • 扩展相同的问题,数据再次为GeoJSON格式,查询的形式为旧式坐标对的形式。您需要更改查询参数,以便不再失败:
db.points.find({point:{
    $ near:{
        $ geometry:{ 
            类型:“点”, 
            坐标:[-84.26060492426588,30.45023887165371]
        }
    }
}})

请参阅有关的文档 $near