【问题标题】:How to use "MongoDB\Driver\Query($filter, $options)"?如何使用“MongoDB\Driver\Query($filter, $options)”?
【发布时间】:2019-06-13 12:28:46
【问题描述】:

我正在尝试使用 MongoDB\Driver\Query 类在 PHP 中进行查询,但使用 php.net 中的文档我并不真正了解如何使其工作。 我想返回一个包含我收藏的所有数据的 JSON 对象。

这适用于使用 PHP 7.1.2 和 MongoDB 3.2.20 运行的函数 PHP

$m = new MongoDB\Driver\Manager("mongodb://login:password@127.0.0.1:27017/");

$filter = array('id' => 0);
$options = array(
    'projection' => ['name' => $parameters['baseName']]
);

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $m->executeQuery(''db_name.my_collection', $query);

$myJson = json_decode(json_encode($cursor),true);

【问题讨论】:

  • 您是否收到任何错误或结果?你的模型是什么样的?
  • 这似乎与答案stackoverflow.com/a/14232565/612175有关,它说使用 json_encode(iterator_to_array($cursor)) 来解决它。

标签: php mongodb php-7.1 php-mongodb


【解决方案1】:

你可以像here说的那样使用它:

json_encode(iterator_to_array($cursor))

【讨论】:

    【解决方案2】:
    try
        {
            $client = new MongoDB\Driver\Manager("mongodb://login:password@127.0.0.1:27017/");
        }
        catch (Exception $e)
        {
            echo "***DB Client not created*** " . $e->getMessage();
            saveEvent("DB Client not created" . $e->getMessage(), $owner);
            exit();
        }
        $filter = ['id'=> $lookForID];
        $query = new MongoDB\Driver\Query($filter);
        try
        {
            $rows = $client->executeQuery('dbName.collectionName', $query);
        }
    catch (Exception $e)
        {
            echo "***search failed*** " . $e->getMessage();
            exit();
        }
        foreach($rows as $r){
           print_r($r);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      相关资源
      最近更新 更多