dongwen5336 2013-01-03 01:21
浏览 84
已采纳

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

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).

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 }
] )

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
));

The error from the above PHP code is:

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

Any ideas? Thanks.

  • 写回答

1条回答 默认 最新

  • doutang7414 2013-01-03 01:27
    关注

    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
        )
    ));
    

    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 ]
    ]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条