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

时间:2014-04-20 23:51:29

标签: mongodb geospatial 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}
}

并且使用mongod我尝试了命令:

db.bar.find({point: {$near: [-84.26060492426588, 30.45023887165371]}});

但是我收到了这个错误:

  

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

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

db.bar.ensureIndex({a:1});
db.bar.ensureIndex({geo:"2d"});

5 个答案:

答案 0 :(得分:67)

很少有问题,你在foo数据库的foo集合上创建了索引,但是正在查询bar集合。你需要在正确的集合上。

阅读您插入的文件,您需要添加一个" 2dsphere"索引到support the geoJson objects。这个指数需要在"点"你的文件的元素,所以尝试

db.bar.createIndex({point:"2dsphere"});

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

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

答案 1 :(得分:8)

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

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

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

可以找到关于相同内容的一些讨论here

答案 2 :(得分:6)

所以这里似乎有一些错误:

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

不"失败"因为目前还没有一个名为" geo"并且具有数据的字段应该在那个地方。如果您使用过" point"相反,这是正确的字段,那么你会收到一个错误,告诉你这种类型的索引对于GeoJSON数据是无效的。你需要一个" 2dsphere"指数:

db.points.createIndex({ "point": "2dsphere" })
  • 扩展同样的问题,数据再次采用GeoJSON格式,查询形式是传统坐标对。您需要更改查询参数,以便不再失败:
db.points.find({point: {
    $near: {
        $geometry:{ 
            type: "Point", 
            coordinates: [-84.26060492426588, 30.45023887165371]
        }
    }
}})

请参阅$near

的文档

答案 3 :(得分:1)

除上述答案外,如果您已经尝试创建索引并且语法或字段错误,则可以运行

db.<yourcollection>.dropIndexes(); 清理所有索引并正确地重新创建它们。

此外,索引应该在&#34;坐标&#34;的父级上创建,而不是在坐标本身上创建:

{
   "_id": 59ac03d168eaaa14c2a57a00",
   "location":{
      "type":"Point",
      "coordinates":[
         131.6667,
         57.8368
      ]
   },
   "age":53,
   "username":"Brandi_Greenfelder"
}

db.<yourcollection>.createIndex({ location: '2dsphere' });

注意,有&#34; 2d&#34;和&#34; 2dsphere&#34;,使用第二个,因为它是新事物。

答案 4 :(得分:0)

如果您使用猫鼬进行连接,这将是正确的答案:

db.collections.<yourcollection>.createIndex({ location : "2dsphere" })

请注意在集合本身之前有一个“集合”属性。如果它不起作用,请检查 console.log 中的 db 对象:

console.log(db)