Untuk semua waktu tanggal yang terhubung dengan kueri, Anda perlu $ memproyeksikan nilainya dari bidang tanggal - manual di sini
Kerangka kerja agregasi datang dengan bantuan dalam kasus ini - silakan lihat kueri dasar di bawah ini, yang memiliki agregat bobot harian dan mingguan, sehingga Anda dapat mengubah kueri ini untuk periode waktu lain atau menggunakan satu kueri per periode:
db.timing.aggregate([{
$project : {
year : {
$year : "$date"
},
month : {
$month : "$date"
},
week : {
$week : "$date"
},
day : {
$dayOfWeek : "$date"
},
_id : 1,
weight : 1
}
}, {
$group : {
_id : {
year : "$year",
month : "$month",
week : "$week",
day : "$day"
},
totalWeightDaily : {
$sum : "$weight"
}
}
},
{
$group : {
_id : {
year : "$_id.year",
month : "$_id.month",
week : "$_id.week"
},
totalWeightWeekly : {
$sum : "$totalWeightDaily"
},
totalWeightDay : {
$push : {
totalWeightDay : "$totalWeightDaily",
dayOfWeek : "$_id.day"
}
}
}
}, {
$match : {
"_id.month" : 3
}
}
])
Contoh hasil untuk bulan 3 untuk data dummy saya di bawah ini:
{
"_id" : {
"year" : 2016,
"month" : 3,
"week" : 10
},
"totalWeightWeekly" : 600,
"totalWeightDay" : [
{
"totalWeightDay" : 200,
"dayOfWeek" : 7
},
{
"totalWeightDay" : 400,
"dayOfWeek" : 6
}
]
}
{
"_id" : {
"year" : 2016,
"month" : 3,
"week" : 9
},
"totalWeightWeekly" : 1000,
"totalWeightDay" : [
{
"totalWeightDay" : 200,
"dayOfWeek" : 4
},
{
"totalWeightDay" : 600,
"dayOfWeek" : 3
},
{
"totalWeightDay" : 200,
"dayOfWeek" : 7
}
]
}
{
"_id" : {
"year" : 2016,
"month" : 3,
"week" : 12
},
"totalWeightWeekly" : 400,
"totalWeightDay" : [
{
"totalWeightDay" : 200,
"dayOfWeek" : 7
},
{
"totalWeightDay" : 200,
"dayOfWeek" : 2
}
]
}
{
"_id" : {
"year" : 2016,
"month" : 3,
"week" : 13
},
"totalWeightWeekly" : 200,
"totalWeightDay" : [
{
"totalWeightDay" : 200,
"dayOfWeek" : 3
}
]
}
dan untuk membentuk bentuk sesuai kebutuhan Anda dapat menggunakan $fase proyek
{$project:{
_id:0,
"year" : "$_id.year", //this could be ommited but use $match to avoid sum of other years
"month" : "$_id.month", //this could be ommited but use $match to avoid sum of other months
"week" :"$_id.week",
totalWeightWeekly:1
}}
{
"totalWeightWeekly" : 600,
"year" : 2016,
"month" : 3,
"week" : 10
}
Setiap komentar diterima!