这是每周分组数据的方法:
transactions.aggregate({
[
{$match: {status: "committed"}},
{$group: {
_id: {
$year: "$date",
$week: "$date"
},
count: {$sum: 1},
start_date: {$min: "$date"},
end_date: {$max: "$date"}
}}
]
});
问题是,如何每两周进行一次分组并获得统计数据?
谢谢。
感谢Mzzl,这适用于每两周一次的分组。以下是完整版本。
db.transactions.aggregate([
{$match: {status: "committed"}},
{$project: {
twoweekperiod: {
$subtract: [
{$week: "$date"}, {$mod: [{$week: "$date"}, 2] }
]
},
date:1,
status:1
}},
{$group: {
_id: {
year: {$year: "$date"},
twoweek: "$twoweekperiod"
},
count: {$sum: 1},
start_date: {$min: "$date"},
end_date: {$max: "$date"}
}}
])
答案 0 :(得分:9)
假设$ week包含周数,您可以创建一个“每两周一次”的数字,并按此分组。尝试这样的事情:
{
$project: {
twoweekperiod: {
$subtract: [
'$week', {$mod: ['$week', 2] }
]
}, status:1, date:1, etc...
}
}
我不知道在mongo查询中进行整数除法的方法,所以我从周数中减去weeknumber mod 2
,得到一个每隔一周而不是每周更改的数字。然后,您可以尝试按此编号进行分组。