【问题标题】:php7 display document stored in mongodb 3.4php7显示存储在mongodb 3.4中的文档
【发布时间】:2017-11-11 17:00:17
【问题描述】:

我对 php 和 mongodb 很陌生。我已经在 Ubuntu 16.04.3 LTS 上安装了 php7.0 和 mongo 3.4.10。

我可以通过输入 mongo cli 命令显示所需的文档: db.testcollection.find({_id:'superid'}).pretty()

它给了我这个结果:

{ "_id" : "superid", "record" : "whatever" }

但我正在尝试使用此 php 脚本显示来自 mongodb 集合的文档:

    <?php

    $mongo = new \MongoDB\Driver\Manager();
    $filter = ['_id' => 'superid'];
    $options = [];
    $query = new \MongoDB\Driver\Query($filter, $options);
    $rows = $mongo->executeQuery('db.testcollection', $query);
    foreach ($rows as $document) {
      print_($document);
      var_dump($document);
      echo $document;
    }

    echo "The END"
    ?>

这只会显示“The END”。

我的 php 脚本中缺少什么来显示 mongo 查询结果,类似于 cli 命令?

【问题讨论】:

    标签: php mongodb


    【解决方案1】:

    问题是: 我在 mongo shell 中使用以下命令创建了名为 test 的新数据库:

    use test;
    db.createCollection("testcollection");
    db.testcollection.insert({ "_id" : "superid", "record" : "whatever"});
    

    所以 db 的路径是 test.testcollection 而不是 db.testcollection。

    当我像这样更正适当的行时:

     $rows = $mongo->executeQuery('test.testcollection', $query);
    

    它按预期工作。

    我被 mongo shell (cli) 弄糊涂了,它不需要指定数据库名称就可以得到正确的结果(即使在注销 mongo shell 并再次登录之后)。

    另一方面,您必须在 php 中指定 dbname.collectionname(这很有意义):)

    【讨论】:

      猜你喜欢
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 2016-10-27
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多