dariusriggins
dariusriggins

Reputation: 1444

Null result for projected _id of created property on Mongo Aggregation query

So I'm trying to get an average broke down by month for my data, and followed the pattern I saw on a few SO posts, but it's coming back as null for the _id result and I can't seem to understand why. The date in my model is indeed a Date type.

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

Upvotes: 1

Views: 523

Answers (1)

Kay
Kay

Reputation: 3012

the pipeline operator expressions for $project and $group must be enclosed in a curly brace like the $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'}
  }
}
)

Upvotes: 2

Related Questions