我想根据小组赛阶段的项目过滤我的数据,项目等于“报告”,那么比较应该是$lt: ['createdAt', 3]
,如果是“历史”,它应该是$lt: ['createdAt', 5]
.考虑到我除了报告和历史之外还有很多项目。如何在管道中实现它?
这是我的样本收集数据:
[
{
s3Url: 1,
item: "report",
sid: "x",
createdAt: 4,
},
{
s3Url: 2,
item: "report",
sid: "x",
createdAt: 3,
},
{
s3Url: 3,
item: "report",
sid: "y",
createdAt: 2,
},
{
s3Url: 4,
item: "history",
sid: "x",
createdAt: 8,
},
]
这是我的尝试:
db.collection.aggregate([
{
$match: {
sid: "x"
}
},
{
$group: {
_id: "$item",
s3Urls: {
$push: {
$cond: [
{
$lt: [
"$createdAt",
5
]
},
"$s3Url",
"$$REMOVE"
]
}
},
}
},
])
答案 0 :(得分:1)
是的,让我们在这里设置一个开关。
db.collection.aggregate([
{
$match: {
sid: "x"
}
},
{
"$project": {
s3Url: 1,
item: 1,
sid: 1,
createdAt: 1,
expiry: {
"$switch": {
"branches": [
{
"case": {
"$eq": [
"$item",
"report"
]
},
"then": 4
},
{
"case": {
"$eq": [
"$item",
"report"
]
},
"then": 5
}
],
"default": 10
}
}
}
},
{
$group: {
_id: "$item",
s3Urls: {
$push: {
$cond: [
{
$lt: [
"$createdAt",
"$expiry"
]
},
"$s3Url",
"$$REMOVE"
]
}
},
}
},
])