紧接着上篇来,这篇主要讲,mongodb的group功能,做的还是挺强大的,相当对于find(),skip(),distinct()等,用法比较复杂。
测试数据
代码如下 | 复制代码 |
> db.fruit.find(); > db.fruit.group( |
php代码如下
代码如下 | 复制代码 |
$keys = array("category" => 1); > db.fruit.group( |
php代码如下:
代码如下 | 复制代码 |
$keys = array("category" => 1); $initial = array("items" => array(),'count'=>0); $reduce = "function (obj, prev) { " . "prev.items.push(obj.name); " . "prev.count++;" . "}"; $condition = array('condition' => array("_id" => array( '$gt' => 2))); $g = $collection->group($keys, $initial, $reduce, $condition); print_r($g); //结果如下。 Array ( [retval] => Array ( [0] => Array ( [category] => fruit [items] => Array ( [0] => banana ) [count] => 1 ) [1] => Array ( [category] => veggie [items] => Array ( [0] => corn [1] => broccoli ) [count] => 2 ) ) [count] => 3 [keys] => 2 [ok] => 1 ) |
3,利用aggregate group功能,也挺强大
代码如下 | 复制代码 |
> db.fruit.aggregate([ { $match: { _id: {$gt:0} } }, { $group: { _id: "$category", count: { $sum: 1 } } }, { $sort: { count: -1 } } ]); { "_id" : "fruit", "count" : 3 } { "_id" : "veggie", "count" : 2 } |
php代码如下:
代码如下 | 复制代码 |
$cond = array( array( '$match' => array('_id' => array('$gt' => 0)), ), array( '$group' => array( '_id' => '$category', 'count' => array('$sum' => 1), ), ), array( '$sort' => array("count" => -1), ), ); $result = $collection->aggregate($cond); print_r($result); //结果如下: Array ( [result] => Array ( [0] => Array ( [_id] => fruit [count] => 3 ) [1] => Array ( [_id] => veggie [count] => 2 ) ) [ok] => 1 ) |
mongodb 的select 操作有很多,在这里,只是说了一些常用的功能。