sandip kakade
sandip kakade

Reputation: 1356

How to calculate average per day field using MongoDB?

I have to calculate per day average of collection filed. I created one query on per minute basis. Now I want to convert this query in per day average. My per minute query as follows

 db.voltage.aggregate(
{
  $unwind: {
        path:"$KeyValues",
        includeArrayIndex:"arrayIndex",
        preserveNullAndEmptyArrays:true
    }
},
{
  $project: {
          timestamp:{
"$add":["$EventTS",{"$multiply":[60000,"$arrayIndex"]}]
          } ,
        "RVoltage":"$KeyValues.RVoltage",
        arrayIndex:1,
        }
},
{
  $match: {
      $and: [
          {RVoltage: {$ne: null}}
       ]
  }
}
);

Can you suggest me how to calculate average per day?

Upvotes: 1

Views: 2872

Answers (1)

Maxim Pavlov
Maxim Pavlov

Reputation: 86

Group by date

db.voltage.aggregate([
    {$project: {
        date: {$dateToString: {format: "%Y-%m-%d", date: "$EventTS"}},
        KeyValues:1
    }},
    {$unwind: '$KeyValues'},
    {$project: {
       date: 1,
       RVoltage: '$KeyValues.RVoltage'
    }},
    {$group: {
        _id: '$date',
        avg: {$avg: '$RVoltage'}
    }},
    {$sort: {_id: 1}}
])
{ "_id" : "2015-07-02", "avg" : 234.1845454545454 }
{ "_id" : "2016-06-30", "avg" : 249.9316666666667 }
{ "_id" : "2016-07-01", "avg" : 244.08681818181822 }

Upvotes: 3

Related Questions