MONGODB::COMMAND与PHP

最近用mongoDB做了一个类似mysql中group by的实做:

一个collection,里面结构为:

节点 id :某物品Id

节点 date :该物品购买日期

节点 num : 该物品在该天的购买次数

里面的记录类似于:

array(’id’=>12345,’date’=>’2010-08-26′,’num’=>12)

array(’id’=>54321,’date’=>’2010-08-26′,’num’=>2)

array(’id’=>12345,’date’=>’2010-08-25′,’num’=>1)

array(’id’=>23456,’date’=>’2010-08-26′,’num’=>6)

如果我要查询每个物品一共被卖出去多少,mysql中我们会这样写:SELECT `id`,sum(num) as total FROM `tablename`  GROUP BY `id`;

那么在mongo中怎么做呢?

可以用 MongoDB::command来做:

$mdb = $mo->mydb;

 

$command = array(
‘group’=>array(
‘ns’ => ‘tmp_token_stat’,
‘key’=>array(’id’=>true),
‘$reduce’ => ‘function (obj, prev) { prev.sum += obj.num;}’,
‘initial’ => array(’sum’ => 0),
),
);
$rs = $mdb->command($command);
mongoDB的官方手册在:http://www.mongodb.org/display/DOCS/Aggregation
php的官方手册在:http://www.php.net/manual/en/mongodb.command.php