Начиная с версии 3.6
Вы должны извлечь год и месяц из вашей даты.
попробуйте ниже агрегации
db['02'].aggregate(
[
// Stage 1
{
$match: {
$expr: {$and:[
{$eq:[{$year:"$CreateDate"},{$year:new Date()}]},
{$eq:[1,{$subtract:[{$month:new Date()},{$month:"$CreateDate"}]}]},
]}
}
},
// Stage 2
{
$group: {
_id:{year:{$year:"$CreateDate"},month:{$month:"$CreateDate"}},
avg : {$avg:"$cummulativeKWH"}
}
},
],
);
До версии 3.6
Вы можете использовать $ redact stage:
дб ['02' ]. Агрегатный (
// Pipeline
[
// Stage 1
{
$group: {
_id:{year:{$year:"$CreateDate"},month:{$month:"$CreateDate"}},
avg : {$avg:"$cummulativeKWH"},
}
},
// Stage 2
{
$redact: {
$cond: { if: { $and:[
{$eq: [ "$_id.year", {$year:new Date()} ]},
{$eq: [-1, {$subtract:[ "$_id.month", {$month:new Date()} ]}]}
]},
then: "$$KEEP",
else: "$$PRUNE"
}
}
},
],
);
Результат:
{
"_id" : {
"year" : NumberInt(2018),
"month" : NumberInt(8)
},
"avg" : 369.0
}