【问题标题】:mongodb's find over nodejs 2d index with $near returns as an empty findmongodb 在 nodejs 2d 索引上的查找,$near 返回为空查找
【发布时间】:2013-05-24 23:06:53
【问题描述】:

我正在尝试从我的地点集合中获取一些接近坐标的结果。为此,我在 location.position 属性上使用了二维索引,该属性具有 lng 和 lat 属性。

问题是我放置的每个坐标,它返回相同的 60 个结果(整个集合)。

我收藏中的文档都来自我的 GPS 坐标附近,但是,如果我放置一个 0.0、0.0 坐标或任何其他对,它总是返回相同的。

事实上,如果我使用空的 find(),查询返回的结果完全相同。

索引似乎已正确创建,因为它没有返回任何错误。

我的收藏中的一个对象是这样的:

{ "_id" : "80293840923...", 
"name": "myname", 
"location" : { 
"position" : { "lng": -196988, "lat": 43.30594 } 
"address": "example", 
"city": "example"  } 
}

索引是这样创建的:

places_collection.ensureIndex({"location.position": "2d"}, {name: "index2dLocation"}, function(error, indexName){
    callback("", "Indice creado: " + indexName)
});

搜索会是这样的:

places_collection.find( 
{ "location.position" : { $near : [ parseFloat(-123.98) , parseFloat(162.342) ] } }
).toArray(function(error, results) {
          if( error ){ callback(error, "")
          }else{ console.log(results.length); callback(null, results); }
});

最后,如前所述,我的搜索总是返回相同的结果。不管我放一个坐标还是另一个坐标。即使我创建一个空的 find() 也不在乎。

这里有什么帮助吗?我不知道如何让它工作。

非常感谢。

【问题讨论】:

    标签: node.js mongodb find


    【解决方案1】:

    最后,解决方案是添加$maxDistance属性,以避免所有文档都比$maxDistance中的半径更远。

    如果您不放置该属性并且只有 10 个文档位于一个坐标附近,如果您在非常远的坐标中进行查找,它仍将返回相同的 10 个文档,因为您没有更多文档靠近新坐标。

    另外,重要的是要说$maxDistance的单位是,所以这是我的解决方案:https://stackoverflow.com/a/7841830/974828

    要将度数转换为公里,您必须除以 111.12。

    结果如下:

     db.places.find( { loc : { $near : [50,50] , $maxDistance : 1/111.12 } } )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 2013-07-06
      相关资源
      最近更新 更多