【问题标题】:Mongo returning array of arrays instead of objectsMongo返回数组而不是对象
【发布时间】:2018-07-05 05:03:22
【问题描述】:

我有以下问题。我刚刚在我的 aws 帐户中创建了一个具有相同版本的新 mongodb 实例,但来自我的 php 查询的结果以不同的方式出现。

以前我得到一个对象数组,但现在我得到一个数组数组。
例如:

之前:

array(1) {
  [0] =>
  class stdClass#401 (6) {
    public $_id =>
    class MongoDB\BSON\ObjectId#390 (1) {
      public $oid =>
      string(24) "5a685fa82fdc5d031e25451c"
    }
  }
}

现在:

array(1) {
  [0]=>
  object(stdClass)#393 (6) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#390 (1) {
      ["oid"]=>
      string(24) "5a685fa82fdc5d031e25451c"
    }
  }
}

在我使用箭头从 php 访问我的变量之前:

$document->_id;

但是现在,在以这种方式获得结果后,我需要将所有内容更改为:

$document['_id'];

是否有任何设置(php/mongo 服务器)以便我可以像以前一样获得结果?

我使用 php mongo 驱动程序来查询我的数据库 - 例如:

$query = new Query($filter, $options);
/** @var MongoDB\Driver\Manager $manager */
return $manager->executeQuery($collection,$query)->toArray();

谢谢

【问题讨论】:

    标签: php mongodb amazon-web-services php-7.1


    【解决方案1】:

    $cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);

    【讨论】:

    • 发现这是最佳答案,您也可以在 find() 和 findOne() 查询的选项数组中指定它
    【解决方案2】:

    在游标中,您可以使用setTypemap 指定它如何返回结果。我认为['document' => 'stdClass'] 可以解决问题:

    $query = new Query($filter, $options);
    /** @var MongoDB\Driver\Manager $manager */
    $cursor = $manager->executeQuery($collection, $query);
    $cursor->setTypeMap(['document' => 'stdClass']);
    return $cursor->toArray();
    

    【讨论】:

    • ->setTypeMap(['root' => 'object']) 解决了这个问题。谢谢!
    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多