可以使用 $cond 运算符
$month 是<= 3,取值为first
$month是<= 6,取值second
m
o
n
t
h
是
<
=
9
,
取
值
t
h
i
r
d
否
则
,
字
段
q
u
a
r
t
e
r
的
值
为
第
四
"
.
然
后
在
q
u
a
r
t
e
r
字
段
中
输
入
month是<= 9,取值third 否则,字段quarter的值为第四". 然后在quarter字段中输入
month是<=9,取值third否则,字段quarter的值为第四".然后在quarter字段中输入group.
db.collection.aggregate([
{$project:{"date":1,
"quarter":{$cond:[{$lte:[{$month:"$date"},3]},
"first",
{$cond:[{$lte:[{$month:"$date"},6]},
"second",
{$cond:[{$lte:[{$month:"$date"},9]},
"third",
"fourth"]}]}]}}},
{$group:{"_id":{"quarter":"$quarter"},"results":{$push:"$date"}}}
])
复杂化
db.getCollection("organization_message_notice").aggregate(
[{
"$match": {
"createTime":{
"$gt" : ISODate("2022-12-01 17:30:10.346")
}
}
}, {
"$project": {
"onlyCrc": 1,
"streamId": 1,
"createTime": 1,
"createTimeOfCZ": {
"$add": ["$createTime", 8 * 60 * 60 * 1000]
},
}
}, {
//两个project管道
"$project": {
"onlyCrc": 1,
"streamId": 1,
"createTime": 1,
"createTimeOfCZ": 1,
"year": {
"$year": ["$createTimeOfCZ"]
},
"month": {
"$month": "$createTimeOfCZ"
},
"week": {
"$week": "$createTimeOfCZ"
},
"day": {
"$dayOfMonth": "$createTimeOfCZ"
},
"hour": {
"$hour": "$createTimeOfCZ"
},
"quarter": {
"$cond": [{
"$lte": [{
"$month": "$date"
}, 3]
}, "first", {
"$cond": [{
"$lte": [{
"$month": "$date"
}, 6]
}, "second", {
"$cond": [{
"$lte": [{
"$month": "$date"
}, 9]
}, "third", "fourth"]
}]
}]
}
}
}, {
"$group": {
"_id": {
"onlyCrc": "$onlyCrc",
"streamId": "$streamId",
"year": "$year",
"quarter" : "$quarter"
// "month": {
// "$month": "$createTimeOfCZ"
// },
// "day": {
// "$dayOfMonth": "$createTimeOfCZ"
// }
},
"onlyCrc": {
"$first": "$onlyCrc"
},
"streamId": {
"$first": "$streamId"
},
"year": {
"$first": "$year"
},
"quarter" : {
"$first" : "$quarter"
},
"month": {
"$first": "$month"
},
"day": {
"$first": "$day"
},
"createTime": {
"$min": "$createTime"
},
"createTimeOfCZ": {
"$min": "$createTimeOfCZ"
},
"count": {
"$sum": 1
}
}
}, {
"$project": {
"_id": 0
}
}, ]
)