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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章