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}
}])

猜你喜欢

转载自lobin.iteye.com/blog/2435437