MongoDB:aggregate与aggregateCursor
环境
mongos 3.0.14
mongos 3.0.14
aggregate
使用 aggregate 可以实现较为复杂的数据聚合操作,例如 汇总(count)、去重汇总(distinct count)、分组统计(group having)等。
aggregate 返回结果为数组,需要注意数据大小不能超过16M。
例如:
$pipeline = [ ['$match' => $tmpCondition], ['$group' => [ '_id' => ['user_id'=>'$user_id'] ]], ['$group' => [ '_id' => '_id.user_id', 'number' => ['$sum'=>1] ]] ]; $options = [ 'allowDiskUse'=>true, 'cursor'=>['batchSize'=>1] ]; $data = MongoSvc::get('user')->user_info->aggregate($pipeline,$options);
aggregateCursor
对于大量返回结果的聚合,可以使用 aggregateCursor 返回游标,可以避免数据大小超限。
aggregateCursor 的返回结果为游标,可循环取数。
例如:
$pipeline = [ ['$match' => $matchArr], ['$project' => ['id'=>1,'_id'=>0]], ['$group' => [ '_id' => '$id', 'count' => ['$sum' => 1] ]], ['$match' => [ 'count' => ['$gt' => 1] ]] ]; //这里改为aggregateCursor用游标循环获取 $data = MongoSvc::get('user')->user_info->aggregateCursor($pipeline);
pipeline 参数
- $match
条件匹配。 - $addFields
增加新字段。 - $count
该stage的文档总数。 - $group
分组。 - $limit
限制数量。 - $skip
跳步。 - $sort
排序。 - $out
输出结果到集合。 - $project
过滤字段。
https://docs.mongodb.com/manu...
options 参数
- explain boolean
处理信息。 - allowDiskUse boolean
true 可往磁盘写临时数据。 - cursor
cursor: { batchSize: <int> }
给返回集合设置一个初始大小。 - hint string or document
强制指定索引。
https://docs.mongodb.com/manu...
查询示例
汇总统计文档中某个字段(如'sum')的count值:
$pipeline = [ ['$match' => $tmpCondition], ['$group' => [ '_id' => ['sum'], 'sum_value' => ['$sum' => '$money'] ]] ];
某列的去重后的数据:
$pipeline = [ ['$match' => $tmpCondition], ['$group' => [ '_id' => ['user_id' => '$user_id'] ]] ];
统计某列(如'user_id')去重后的count值:
$pipeline = [ ['$match' => $tmpCondition], ['$group' => [ '_id' => ['user_id'=>'$user_id'] ]], ['$group' => [ '_id' => '_id.user_id', 'number' => ['$sum'=>1] ]] ]; $pipeline = [ ['$match' => $tmpCondition], ['$group' => [ '_id' => ['qid' => '$qid'], 'max_number' => ['$max' => '$days'] ]], ['$group' => [ '_id' => ['number' => '$max_number'], 'total' => ['$sum' => 1] ]] ];
统计分组后,各组内的某列汇总值:
$pipeline = [ ['$match' => $tmpCondition], ['$group' => [ '_id' => ['type' => '$type'], 'sum_value' => ['$sum' => '$number'] ]] ];
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19