Dharmik soni
Dharmik soni

Reputation: 363

Mongo Aggregate - Calculating based on dates

Here is a sample document.

{"_id":{"$oid":"5e557779ed588826d84cef11"},
"meter_id":"1001",
"date":{"$date":{"$numberLong":"1509474600000"}},
"parameter_name":"hvac","voltage":{"unit":"V"},
"current":{"unit":"AMP"},
"powerFactor":{"unit":"phi"},
"angle":{"unit":"degree"},
"activePower":{"unit":"kwh"},
"reactivePower":{"unit":"kwh"},
"apparentPower":{"unit":"kwh"},
"frequency":{"unit":"hz"},
"thd":{"unit":"percentage"},
"energy":{"Energy":"5.7"},
"power":{"unit":"watt"},

And there are around 100 000 documents. I want to filter out the documents whose date is greater than the date i specify and calculate the total energy i.e energy.Energy

I used the below aggregation, but it doesn't seem to be working

const endDate = new Date(12-12-2018)
 MeterData.aggregate([
      {
          $group: {
              _id: "$meter_id",
              total: { $sum: 1 },
              totalEnergy: { $sum: { $toDouble: "$energy.Energy"
                   } },
                   dateSum: {
                    $sum: {
                      $toDouble: {
                        $not: [{
                          $cond: {
                            if: {
                              $gte: [
                                "$date", endDate
                              ]
                            },
                            then: "$energy.Energy",
                            else: 0
                          }
                        }

                        ]


                    }
                    }
                   }
          }
      }
  ])

Upvotes: 0

Views: 68

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59513

Would be this:

db.collection.aggregate([
   { $match: { date: { $gte: ISODate("2016-12-12") } } },
   {
      $group: {
         _id: "$meter_id",
         total: { $sum: 1 },
         totalEnergy: { $sum: "$energy.Energy" }
      }
   }
])

See Mongo playground

Upvotes: 1

Related Questions