mongodb中的maxDistance:通过数据查找附近的问题

时间:2016-05-23 08:31:54

标签: mongodb geolocation location mongodb-query

我的mongo版本是3.2.6

我的餐桌是restaurant_locations。

我给出的指数如下:

db.restaurant_locations._ensureIndex({'location': '2dsphere'});

此表中存储的数据如下:

> db.restaurant_locations.find().pretty();
{
        "_id" : ObjectId("573ff477df3c12bdd6463d07"),
        "location" : {
                "type" : "Point",
                "coordinates" : [
                        72.5220332,
                        23.0656791
                ]
        }
}
{
        "_id" : ObjectId("573ff5badf3c12bdd6463d08"),
        "location" : {
                "type" : "Point",
                "coordinates" : [
                        62.5220332,
                        13.0656791
                ]
        }
}

现在当我在查询下面开火时:

db.restaurant_locations.find({
  location: {
    $near: {
        $geometry: {
          type: 'Point',
          coordinates: [ 70, 20 ]
        },
    $maxDistance: 100000000
    }
  }
});

我得到两个记录作为输出:

{ "_id" : ObjectId("573ff477df3c12bdd6463d07"), "location" : { "type" : "Point", "coordinates" : [ 72.5220332, 23.0656791 ] } }
{ "_id" : ObjectId("573ff5badf3c12bdd6463d08"), "location" : { "type" : "Point", "coordinates" : [ 62.5220332, 13.0656791 ] } }

现在,当我执行以下查询时:

db.restaurant_locations.find({
  location: {
    $near: {
        $geometry: {
          type: 'Point',
          coordinates: [ 70, 20 ]
        },
    $maxDistance: 1000000
    }
  }
});

我只输出一条记录:

{ "_id" : ObjectId("573ff477df3c12bdd6463d07"), "location" : { "type" : "Point", "coordinates" : [ 72.5220332, 23.0656791 ] } }
  1. 我无法确切了解$ maxDistance的工作原理。
  2. 我想在距离10公里的地方找到餐馆,那么究竟是什么东西,我需要传递$ maxDistance?
  3. 假设我的坐标是40和20,所以如果我想要10kms以内的餐馆,会显示以上两个记录吗?
  4. 我已经提到了许多mongodb文档,stackoverflow问题,但我没有得到确切的想法,它是如何工作的

    提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

I am not getting exactly how $maxDistance work.

为了获得maxDistance工作,您必须使用$nearSphere函数

您的查询将是这样的:

location: {
    $nearSphere: {
        $geometry: {
          type: 'Point',
          coordinates: [ 70, 20 ]
        },
    $maxDistance: 10000
    }
  } 

I want to find restaurants within a distance of 10 kms,

你需要乘以1000,因为mongo分辨率以米为单位

Suppose my co-ordinates are 40 and 20, so if I want restaurants within 10kms, will above two records display?

是的,但您必须先确定先指定经度,然后再指定纬度。