【问题标题】:problems with php7 mongo query findOnephp7 mongo 查询 findOne 的问题
【发布时间】:2017-06-29 15:54:35
【问题描述】:

我有 ubuntu 16.04、php7 和 mongo。

更新系统后,我的代码不起作用...我有一个新版本的php。

更新之前,我的代码是:

  // connect
  $m = new MongoClient();
  // select a database
  $db = $m->clients;
  // select a collection (analogous to a relational database's table)
  $collection = $db->suscriptions;
  // Check if exists in DB
  $query = array('email' => $email);
  $cursor = $collection->findOne($query);

更新后,我按照 php 文档的指示更改了连接,但我无法进行任何查询... 这是我的代码,如果我删除最后一行,代码就可以工作:

  // connect
  $m = new MongoDB\Driver\Manager("mongodb://localhost:27017");
  // select a database
  $db = $m->clients;
  // select a collection (analogous to a relational database's table)
  $collection = $db->suscriptions;
  // Check if exists in DB
  $query = array('email' => $email);
  // Problem
  $cursor = $collection->findOne($query);

你能帮帮我吗?谢谢!

【问题讨论】:

    标签: php mongodb ubuntu


    【解决方案1】:

    你使用的 manager api 不正确。

    $m = new MongoDB\Driver\Manager("mongodb://localhost:27017");
    $filter= array('email' => $email);
    $options = array(
      'limit' => 1
    );
    $query = new MongoDB\Driver\Query($filter, $options);
    $rows = $m->executeQuery('clients.suscriptions', $query);
    

    或者,您应该通过 composer 安装库,它提供与旧 api 类似的语法。

    require 'vendor/autoload.php';
    $m= new MongoDB\Client("mongodb://127.0.0.1/");
    $db = $m->clients;
    $collection = $db->suscriptions;
    $query = array('email' => $email);
    $document = $collection->findOne($query);
    

    https://docs.mongodb.com/php-library/master/tutorial/crud/#find-one-document

    【讨论】:

      【解决方案2】:

      对于那些想在新的 Mongo 库和 PHP7 之间使用简单包装器的人,我正在我的 GitHub 上维护一个。

      https://github.com/ThomasSquall/PHP7MongoDriver

      此外,如果您想为存储库本身做出贡献,欢迎您:)

      【讨论】:

        【解决方案3】:

        只是在尝试直接print_r 结果时花了一些时间认为这不起作用,如果只是测试代码,则必须将光标转换为数组才能显示为:

        $result = $this->OMongo->executeQuery("db.collection", $query);
        print_r(iterator_to_array($result), false);
        

        【讨论】:

          猜你喜欢
          • 2021-11-14
          • 2017-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-31
          • 1970-01-01
          • 2015-10-26
          相关资源
          最近更新 更多