使用 PHP 驱动程序的 MongoDB 聚合查询

2022-01-20 00:00:00 mongodb aggregation-framework php

我有一个可以通过 MongoDB shell 运行的 MongoDB 聚合查询.但是,我正在尝试将其转换为与官方 PHP Mongo 驱动程序 (http://php.net/manual/en/mongocollection.aggregate.php) 一起使用.

I have a working MongoDB aggregate query which I can run via the MongoDB shell. However, I am trying to convert it to work with the official PHP Mongo driver (http://php.net/manual/en/mongocollection.aggregate.php).

这是有效的原始 MongoDB 查询:

Here is the working raw MongoDB query:

db.executions.aggregate( [  
   { $project : { day : { $dayOfYear : "$executed" } } },
   { $group : { _id : { day : "$day" }, n : { $sum : 1 } } } , 
   { $sort : { _id : -1 } } , 
   { $limit : 14 }
] )

这是我在 PHP 中使用 Mongo 驱动程序的尝试(不工作):

Here is my attempt (not working) in PHP using the Mongo driver:

$result = $c->aggregate(array(
    '$project' => array(
        'day' => array('$dayOfYear' => '$executed')
    ),
    '$group' => array(
        '_id' => array('day' => '$day'),
        'n' => array('$sum' => 1)
    ),
    '$sort' => array(
        '_id' => 1
    ),
    '$limit' => 14
));

上述PHP代码的错误是:

The error from the above PHP code is:

{"errmsg":"exception: wrong type for field (pipeline) 3 != 4","code":13111,"ok":0}

有什么想法吗?谢谢.

推荐答案

您的 Javascript 中的参数是一个由 4 个对象组成的数组,每个对象有一个元素,在您的 PHP 中,它是一个具有 4 个元素的关联数组(对象).这将代表您的 Javascript:

The parameter in your Javascript is an array of 4 objects with one element each, in your PHP it's an associative array (object) with 4 elements. This would represent your Javascript:

$result = $c->aggregate(array(
    array(
      '$project' => array(
          'day' => array('$dayOfYear' => '$executed')
      ),
    ),
    array(
      '$group' => array(
          '_id' => array('day' => '$day'),
          'n' => array('$sum' => 1)
      ),
    ),
    array(
      '$sort' => array(
          '_id' => 1
      ),
    ),
    array(
      '$limit' => 14
    )
));

另外,如果你至少有 PHP5.4,你可以使用更简单的数组语法.转换为 PHP 就很简单了,您只需将花括号替换为方括号,将冒号替换为箭头:

In addition, if you have at least PHP5.4, you can use simpler array syntax. Transformation to PHP is then trivial, you simply replace curly braces with square brackets and colons with arrows:

$result = $c->aggregate([
  [ '$project' => [ 'day' => ['$dayOfYear' => '$executed']  ]  ],
  [ '$group' => ['_id' => ['day' => '$day'], 'n' => ['$sum' => 1]  ] ],
  [ '$sort' => ['_id' => 1] ],
  [ '$limit' => 14 ]
]);

相关文章