1. 程式人生 > >mongodb 計算季度 & 按季度分組統計

mongodb 計算季度 & 按季度分組統計

 

 

計算季度:

 

db.task.aggregate([{
	$match: {
		"createDate": {$ne: null}
	}
}, {
	$project: {
		status: 1, 
		createDate: 1,
		quarter: {
			$cond: {
				if: {
					$gte: [{
						$month: "$createDate"
					}, 10]
				}, 
				then: "Q4", 
				else: {
					$cond: {
						if: {
							$gte: [{
								$month: "$createDate"
							}, 7]
						}, 
						then: "Q3", 
						else: {
							$cond: {
								if: {
									$gte: [{
										$month: "$createDate"
									}, 4]
								}, 
								then: "Q2", 
								else: "Q1"
							}
						}
					}
				}
			}
		}
	}
}])

 

 

按季度分組統計:

 

 

db.task.aggregate([{
	$match: {
		"createDate": {$ne: null}
	}
}, {
	$project: {
		status: 1, 
		createDate: 1,
		quarter: {
			$cond: {
				if: {
					$gte: [{
						$month: "$createDate"
					}, 10]
				}, 
				then: "Q4", 
				else: {
					$cond: {
						if: {
							$gte: [{
								$month: "$createDate"
							}, 7]
						}, 
						then: "Q3", 
						else: {
							$cond: {
								if: {
									$gte: [{
										$month: "$createDate"
									}, 4]
								}, 
								then: "Q2", 
								else: "Q1"
							}
						}
					}
				}
			}
		}
	}
}, {
	$group: {
		_id: {"year": {"$year": "$createDate"}, quarter: "$quarter", status: "$status"}, 
		count: { $sum: 1 }
	}
}, {
	$sort : {"_id.year" : -1, "_id.quarter": -1, "_id.status": -1}
}])