【问题标题】:How to use geoNear with the current PHP MongoDB Driver?如何将 geoNear 与当前的 PHP MongoDB 驱动程序一起使用?
【发布时间】:2017-08-06 11:54:55
【问题描述】:

我目前正在使用当前的PHP MongoDB\Driver

我需要使用geoNear 查询从我当前的位置获取点。所需的2dsphere index 已设置,查询在控制台中运行并提供多个结果:

db.runCommand({geoNear: 'pois', near: [ 52.264633, 6.12485 ], spherical: true, maxDistance: 1000, distanceField: 'distance'})

由于以前的方法已被弃用,我不能使用旧的aggregate 函数。

我现在正试图找到正确的方法来使用当前的 QueryCommand 类构建我需要的查询。

我尝试过的如下:

$query = array(
    'geoNear' => 'pois',
    "near" => array(
        52.264633,
        6.12485
    ),
    "spherical" => true,
    "maxDistance" => 1000,
    "distanceField" => "distance"
);
$cmd = new MongoDB\Driver\Command($query);
$returnCursor = $this->conn->executeCommand("database.pois", $cmd);
$arrReturn = $returnCursor->toArray();
return $arrReturn;

如果我使用这个,我会返回这个运行时错误:

"exception": [
    {
      "type": "MongoDB\\Driver\\Exception\\RuntimeException",
      "code": 18,
      "message": "Failed to decode document from the server."
    } 
]"

我找不到适合我的案例的解决方案,也找不到有关此错误的更多信息。

如果我将Command 更改为Query,执行不会失败,但没有结果。

我的mongodb是3.2版本,我的php版本是php版本7.0.16-4+deb.sury.org~trusty+1,mongodb Exension是1.2.3版本

【问题讨论】:

    标签: php mongodb php-7


    【解决方案1】:

    您可以通过以下方式将聚合与新驱动程序一起使用。

    $pipeline = array(array(
        '$geoNear'=> array(
        'near' => array(
            52.264633,
            6.12485
        ),
        'spherical' => true,
        'maxDistance' => 1000,
        'distanceField' => "distance"
    )));
    
    $cmd = new \MongoDB\Driver\Command([
        'aggregate' => 'pois', 
        'pipeline' => $pipeline
    ]);
    
    $returnCursor = $this->conn->executeCommand("database", $cmd);
    $arrReturn = $returnCursor->toArray();
    

    【讨论】:

    • 你有没有找到这个的来源?我找不到关于这个的东西。但它有效,谢谢。
    • 好吧,我完全忽略了这一点,感谢您为我指明了正确的方向。
    【解决方案2】:

    还有一个Library from Mongo 扩展了驱动程序的默认功能,使其更加用户友好

    但由于它没有内置在 php 网站中,因此很容易错过

    MongoDB\Collection::aggregate($pipeline, $options)

    在哪里

    $pipeline = array(array(
        '$geoNear'=> array(
            'near' => array(
                52.264633,
                6.12485
             ),
            'spherical' => true,
            'maxDistance' => 1000,
            'distanceField' => "distance"
        )
    ));
    

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 2021-12-04
      • 1970-01-01
      • 2018-01-13
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多