【问题标题】:Unable to retrieve records from Mongodb for lat,long with $near query无法通过 $near 查询从 Mongodb 检索 lat、long 的记录
【发布时间】:2016-06-08 01:40:36
【问题描述】:

我对使用 mongodb 进行地理空间数据搜索非常陌生。我需要检索靠近我提供查询的经纬度的英国邮政编码(结果经纬度、经度)。我的mongodb查询如下:

$mongoPostcode = MongoDbConnector::getCollection("postcodes");
$query = array(
'location' => array(
    '$near' => array(
        'latitude' => 57.14270109,
        'longitude' => -2.093014619,
        '$maxDistance' => 15 / 111.12 // 1 degree is approximately 111.12 kilometers. 15 km of 111.12 would be 15/111.12
    )
)
);

$nearByPostcodeData = $mongoPostcode->find($query);

我的 mongo 的原始记录条目如下所示:

{
"_id": {
"$oid": "56ced2e6cffa1906847b6868"
},
"postcode": "AB11 8RQ",
"location": {
"latitude": 57.13597762,
"longitude": -2.072114784
},
"timestamp": 1454601532,
"active_status": 1
}

但是当我进行搜索时,它会返回以下错误:

Fatal error: Uncaught exception 'MongoCursorException' with message 'localhost:27017: Unable to execute query: error processing query: ns=sampleproject.postcodes limit=0 skip=0 Tree: GEONEAR field=location maxdist=0.134989 isNearSphere=1 Sort: {} Proj: {} planner returned error: unable to find index for $geoNear query' in C:\xampp\htdocs\sampleproject\files\php\searchByPostCode.php:35 Stack trace: #0 C:\xampp\htdocs\sampleproject\files\php\searchByPostCode.php(35): MongoCursor->rewind() #1 {main} thrown in C:\xampp\htdocs\sampleproject\files\php\searchByPostCode.php on line 35

示例数据建模中是否缺少任何内容或者是查询问题?

【问题讨论】:

    标签: php mongodb geojson


    【解决方案1】:

    您需要创建一个特殊的索引。 2D Sphere index

    db.postcodes.createIndex( { "location" : "2dsphere" } )
    

    编辑

    您可以修改您的集合以使用米而不是弧度进行查询。

    {
        "_id": { "$oid": "56ced2e6cffa1906847b6868" },
        "postcode": "AB11 8RQ",
        "location": {
            "type": "Point",
            "coordinates": [
                -2.072114784, // Longitude
                57.13597762 // Latitude
            ]
         },
         "timestamp": 1454601532,
         "active_status": 1
     }
    

    您的查询将如下所示:

    $query = array(
        'location' => array(
            '$near' => array(
                'latitude' => 57.14270109,
                'longitude' => -2.093014619,
                '$maxDistance' => 1000 // 1000 meters        )
            )
         )
    );
    

    这需要重塑您的整个收藏。详情可见here

    【讨论】:

    • 嘿,谢谢!它简直太棒了。
    • 还想问你一件事。 $minDistance 和 $maxDistance 的单位是什么?如果我需要在纬度 15 公里范围内找到结果,只要我如何使用它?我用的那个让我很困惑。
    猜你喜欢
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 2015-03-22
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    相关资源
    最近更新 更多