mongodb中的aggregate() 方法详解

按照 支付状态进行分组

db.weixin_pay_log.aggregate([
    {$group:{_id:"$payStatus",count:{$sum:1},total:{$sum:"$sum"}}}
])



支付类型payType = “5” 

db.weixin_pay_log.aggregate([
    {$match:{"payType":"5"}},
    {$group:{_id:"$payStatus",count:{$sum:1},total:{$sum:"$sum"}}}
])



count总数 小于 2500

db.weixin_pay_log.aggregate([
    
    {$group:{_id:"$payStatus",count:{$sum:1},total:{$sum:"$sum"}}},
    {$match:{count:{$lt:2500}}}
])

多字段进行分组

db.weixin_pay_log.aggregate([
    {$group:{_id:{payType:"$payType",payStatus:"$payStatus"},count:{$sum:1}}},
])

$project

db.collection.aggregate([

  {$project:{name:1,status:1}}

]);

结果是,只有_id,name,status三个字段的表数据,相当于sql表达式 select _id,name,status from collection

MongoDB提供了三种执行聚合的方法:Aggregation Pipleline,map-reduce功能和 Single Purpose Aggregation Operations 

aggreagte是一个数组,其中包含多个对象(命令),通过遍历Pipleline数组对collection中的数据进行操作。

$group:聚合的配置

  • _id代表你想聚合的数据的主键,上述数据中,你想聚合所有cust_id相同的条目的amount的总和,那_id即被设置为cust_id_id必须,你可以填写一个空值。

  • total代表你最后想输出的数据之一,这里total是每条结果中amount的总和。

  • $sum是一个聚合的操作符,另外的操作符你可以在官方文档中找到。上图中的命令表示对相同主键(_id)下的amount进行求和。如果你想要计算主键出现的次数,可以把命令写成如下的形式  {$sum: 1}

db.weixin_pay_log.aggregate([
    
    {$group:{_id:{payType:"$payType",payStatus:"$payStatus"},
    count:{$sum:1},
    count_avg:{$avg:"$totalFee"},
    weixinId_first:{$first:"$weixinId"},
    weixinId_last:{$last:"$weixinId"},
    fee_sum:{$sum:"$totalFee"}
    }},
])
db.weixin_pay_log.aggregate([
    {$project:{totalFee:1,weixinId:1,yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$repayRequestTime"} }}},
    {$group:{_id:{date:"$yearMonthDay",payType:"$payType",payStatus:"$payStatus"},
    count:{$sum:1},
    count_avg:{$avg:"$totalFee"},
    weixinId_first:{$first:"$weixinId"},
    weixinId_last:{$last:"$weixinId"},
    fee_sum:{$sum:"$totalFee"}
    }},
])
  • $match 聚合前数据筛选

  • $skip 跳过聚合前数据集的 n 行, 如果 {$skip: 10}, 最后 rows = 5000000 - 10

  • $project 之选择需要的字段, 除了 _id 之外其他的字段的值只能为 1

conversionStage = {
	$project:{
		from:1,
		to:1,
		amount:1,
		timestamp:{
			$convert:{
				input:"$timestamp",
				to:"date",
				onError:{
					$concat:["Could not convert",
							{$toString:"$timestamp"},
							" to type date."]
				},
				onNull:"Missing timestamp."
			}
		}
	}
};

filterStage = {
	$match:{
		timestamp:{"$type","date"}
	}
};

calcStage = {
	$group:{
		_id:{account:"$from",year:{$year:"$timestamp"},month:{$month:"$timestamp"}},
		sum:{$sum:"$account"},
		count:{$sum:1}
	}
};
load(aggregate.js)
db.tranfer.aggregate([conversionStage,filterStage,calcStage]);
Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.sort(Sort.Direction.DESC,"timestamp"),
                Aggregation.project("totalFee", "weixinId","payType","payStatus")
                .and("repayRequestTime").dateAsFormattedString("%Y-%m-%d").as("yearMonthDay"),
                        //.and("repayRequestTime").extractYear().extractMonth().extractDayOfMonth(),
                Aggregation.group("payType","payStatus","yearMonthDay")
        );
      Object object =  mongoTemplate.aggregate(aggregation,"weixin_pay_log",Object.class);
        System.out.println(object);

参考链接:https://blog.csdn.net/qq_39263663/article/details/80459833

mongodb聚合利用日期分组 https://blog.csdn.net/u013066244/article/details/53842355

猜你喜欢

转载自blog.csdn.net/dengwenqi123/article/details/83689813
今日推荐