php - 从 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;
解决方案
那是我的错误。我应该在 json_decode 函数中添加true作为第二个参数,如下所示:
$array = json_decode(json_encode($result->toArray(),true), true);
这会将 BSON 文档转换为数组而不是单行中的 std 对象。
推荐阅读
- google-apps-script - 代码触发器在 App Google Sheets 中不起作用
- ios - iOS Swift 验证收据 JSON 获取问题
- java - 将一些 get 和 set 代码从 C# 转换为 Java
- python - 替换、转换、更改、布尔型 False 和 True 为 0 和 1
- c++ - 是否有另一种选择来打破?
- arrays - Bash - 如何检查变量值是否在数组中
- sql-server - 是否可以通过 Oracle 的异构链接使用 WITH (NOLOCK)
- python - 在数据框列中保留重复项的第一个和最后一个条目
- vue.js - 如何缓存其他路线以供离线浏览?
- azure - 无法使用 AAD 对 Azure Bot 进行身份验证(bot sdk 4)