在我的项目中,我有一个废物收集,它如下
wastes:[
{weight: 100, date: ISODate("2016-01-01T10:20:41.417Z")}
{weight: 100, date: ISODate("2016-01-01T10:20:41.417Z")}
{weight: 100, date: ISODate("2016-02-01T10:20:41.417Z")}
{weight: 100, date: ISODate("2016-02-01T10:20:41.417Z")}
{weight: 100, date: ISODate("2016-03-01T10:20:41.417Z")}
{weight: 100, date: ISODate("2016-03-01T10:20:41.417Z")}
........................................................
{weight: 100, date: ISODate("2016-12-01T10:20:41.417Z")}
{weight: 100, date: ISODate("2016-12-01T10:20:41.417Z")}
]
我想在今年汇总每个月的浪费,如
results: [
<month1>:{weight: 200},
<month2>:{weight: 200},
......................
<month12>:{weight: 200}
]
并且在当前一周和当天按周计算,如下所示
results:[
<week1>:{weight: 100},
.....................
<week4>:{weight: 100}
]
results: [
<day1>:{weight: 100},
....................
<day7>:{weight: 100}
]
注意:明智的和明天的聚合值只是我需要那种输出的虚拟值。
答案 0 :(得分:2)
对于与查询相关的所有日期时间,您需要从日期字段$ {项目值 - manual here
聚合框架在这种情况下提供帮助 - 请参阅下面的基本查询,其中包含每日和每周权重聚合,因此您可以将此查询转换为其他时间段或每个时段使用一个查询:
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
}
}
])
我的虚拟数据的第3个月的示例结果如下:
{
"_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
}
]
}
并根据需要形成形状,您可以使用$ project phase
{$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
}
欢迎任何评论!