首页 > 解决方案 > 从 aggregate() 获取 PHP array() 或将 MongoDB\Driver\Cursor 转换为 array() 的正确方法

问题描述

数据库上的一些文档有“Assunto”字段,我想计算“Assunto”的不同值出现了多少次(忽略该字段不存在时,所以我做了这个查询:

$result = $collection->aggregate([
[ '$match' => ['Assunto' => ['$nin' => [null]]] ],
[ '$sortByCount'=> '$Assunto' ],
[ '$sort' => ['Count' => -1] ]
]);

查询正常工作,我的问题是从聚合返回。从文档中它返回“A MongoDB\Driver\Cursor 或 ArrayIterator 对象”。

同样来自文档typeMap:“可选。应用于游标的类型映射,它确定 BSON 文档如何转换为 PHP 值。默认为集合的类型映射”。

我在 Stack Overflow 上阅读了关于更改集合的 typeMap 以将光标转换为数组的解决方案,但我无法让它们适用于我的情况,据我了解,我有多个 MongoDB\Driver\Cursor 并且它只返回第一个其中。

Stack Overflow 的下一个解决方案是将光标编码为 JSON,然后将其解码为数组。像这样:

//Convert $result, a MongoDB\Driver\Cursor to array()
$objects = json_decode(json_encode($result->toArray(),true));

问题是这会产生一个 stdClass 对象,就像这样:(抱歉,图像模糊,调整大小后发生)

在此处输入图像描述

因此,要将这个 stdClass 转换为数组,我需要再次执行相同的代码:(抱歉,图像模糊,调整大小后发生)

//Convert stdClass to Array
$array=json_decode(json_encode($objects),true);

在此处输入图像描述

这会产生预期的输出。但是做所有这些过程似乎是一种浪费。在我的情况下,将返回值从聚合转换为数组的正确方法是什么?整个代码片段以防万一:

$result = $collection->aggregate([
[ '$match' => ['Assunto' => ['$nin' => [null]]] ],
[ '$sortByCount'=> '$Assunto' ],
[ '$sort' => ['Count' => -1] ]
]);

//Convert $result, multiple MongoDB\Driver\Cursor objects into stdClass Objects
$objects = json_decode(json_encode($result->toArray(),true));

//Convert stdClass Objects into Array()
$array=json_decode(json_encode($objects),true);

return $array;

标签: phpmongodbmongodb-queryaggregation-frameworkmongodb-php

解决方案


那是我的错误。我应该在 json_decode 函数中添加true作为第二个参数,如下所示:

$array = json_decode(json_encode($result->toArray(),true), true);

这会将 BSON 文档转换为数组而不是单行中的 std 对象。


推荐阅读