所以我试图按月对我的数据进行平均分解,并按照我在几个SO帖子上看到的模式,但是对于_id结果它将返回null,我似乎无法理解为什么。我模型中的日期确实是日期类型。
{
$match: {
date: {$gte: startDate, $lte: endDate }
},
$project: {
'date': 1
, 'fatigue.percent': 1
, 'fitness.percent': 1
, 'maintenance.percent': 1
, 'substances.percent': 1
, 'unsafe.percent': 1
, 'created_on': {
month: { '$month': '$date' }
}
}
,$group: {
_id: '$created_on'
, averageFatigue: {$avg : '$fatigue.percent'}
, averageFitness: {$avg : '$fitness.percent'}
, averageMaintenance: {$avg : '$maintenance.percent'}
, averageSubstances: {$avg : '$substances.percent'}
, averageUnsafe: {$avg : '$unsafe.percent'}
}
}
答案 0 :(得分:2)
$ project和$ group的管道运算符表达式必须用大括号括起来,如$ match:
db.test.aggregate(
{
$match: {
date: {$gte: startDate, $lte: endDate }
}
},
{
$project: {
'date': 1
, 'fatigue.percent': 1
, 'fitness.percent': 1
, 'maintenance.percent': 1
, 'substances.percent': 1
, 'unsafe.percent': 1
, 'created_on': {
month: { '$month': '$date' }
}
}
},
{
$group: {
_id: '$created_on'
, averageFatigue: {$avg : '$fatigue.percent'}
, averageFitness: {$avg : '$fitness.percent'}
, averageMaintenance: {$avg : '$maintenance.percent'}
, averageSubstances: {$avg : '$substances.percent'}
, averageUnsafe: {$avg : '$unsafe.percent'}
}
}
)