0

所以我试图让我的数据按月细分,并遵循我在一些 SO 帖子中看到的模式,但是 _id 结果返回为空,我似乎无法理解为什么。我的模型中的日期确实是 Date 类型。

{
$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'}
  }
}
4

1 回答 1

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'}
  }
}
)
于 2013-04-11T22:14:17.077 回答