【问题标题】:MongoDB aggregate - How to use in PHP?MongoDB 聚合 - 如何在 PHP 中使用?
【发布时间】:2021-11-09 18:27:08
【问题描述】:

我在 MongoDB 中使用这个命令,它返回正确的数据:

db.getCollection('school').aggregate([{ $group: { _id: "$initials", total: { $sum: "$total" }}}, { $sort : { _id : 1}}])

但是当我用 PHP 编写该命令时,我得到了错误。我正在尝试:

$mng = new MongoDB\Driver\Manager();
$command = new MongoDB\Driver\Command(['aggregate' => 'school', 'pipeline' => [ '$group' => ['_id' => '$initials', 'count' => [ '$sum' => '$total']], 'cursor' => new stdClass ]]);
$cursor = $mng->executeCommand('school', $command);
var_dump($cursor->toArray()[0]);

有人可以帮我吗?

【问题讨论】:

  • 错误是什么?
  • PHP 致命错误:未捕获的 MongoDB\Driver\Exception\CommandException:'pipeline' 选项必须在 /var/www/html/mongodbtest.php:45 中指定为数组
  • 试试$command = new MongoDB\Driver\Command(['aggregate' => 'school', 'pipeline' => [[ '$group' => ['_id' => '$initials', 'count' => [ '$sum' => '$total']]], 'cursor' => new stdClass ]]);(管道需要“命令”数组,每个都应该是数组)

标签: php mongodb


【解决方案1】:

现在是正确的:

$command = new MongoDB\Driver\Command(['aggregate' => 'school', 'pipeline' => [[ '$group' => ['_id' => '$initials', 'count' => [ '$sum' => '$total']]], [ '$sort' => ['_id' => 1] ],], 'cursor' => new stdClass, ]);

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多