Reputation: 325
This is how to group data weekly :
transactions.aggregate({
[
{$match: {status: "committed"}},
{$group: {
_id: {
$year: "$date",
$week: "$date"
},
count: {$sum: 1},
start_date: {$min: "$date"},
end_date: {$max: "$date"}
}}
]
});
The question is, how about grouping every 2 weeks and get the count?
Thank you.
Thanks to Mzzl, this works for grouping every 2 weeks. Below is the complete version.
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"}
}}
])
Upvotes: 15
Views: 3214
Reputation: 4136
Assuming $week contains the week number, you can create an 'every two weeks' number, and group by that. Try something like this:
{
$project: {
twoweekperiod: {
$subtract: [
'$week', {$mod: ['$week', 2] }
]
}, status:1, date:1, etc...
}
}
I don't know of a way to do an integer divide in a mongo query, so instead I subtract weeknumber mod 2
from the weeknumber, to get a number that changes every other week instead of every week. You could then try grouping by this number.
Upvotes: 9