2016-02-19 28 views
0

我在Robomongo/cli中使用此查询来获取距离给定的坐标正确工作的记录。如何获得从MongoDB查询时的距离(地理空间概念)

现在我该如何获得相同查询的距离?

下面是我的查询

db.places.find(
{ 
    loc : 
    { 
     $near : 
     { 
      $geometry : 
      { 
       type : "Point", 
       coordinates : [12.974729, 77.609375], 
       $maxDistance : 2000 
      } 
     } 
    } 
) 

JSON文件

{ 
    "_id" : ObjectId("56c6becd8586e7a757260d62"), 
    "name" : "address here", 
    "loc" : { 
     "type" : "Point", 
     "coordinates" : [ 
      12.9802900000000001, 
      77.5857400000000013 
     ] 
    } 
} 

回答

1

可以使用GeoNear命令返回统计数据,包括average distance

db.runCommand({ 
    geoNear: "places" , 
    near: { type: "Point", coordinates: [12.974729, 77.609375] }, 
    spherical: true, 
    maxDistance: 2000 
}).stats.avgDistance 
+0

我不能运行它给“没有地理索引:(“错误。我正在使用mongo 2.2.0版本号 – Sharath

+0

您需要使用地理索引才能使用地理空间查询。 –

+0

这是命令db.places.ensureIndex({'loc':“2dsphere”});应该用来创建地理索引。我的json文档在文章中更新 – Sharath

相关问题