MongoDB aggregation mechanism - how to compare by date, group by day and return daily averages?

I am just studying the MongoDB aggregation structure and I wonder if anyone can help me improve this query to do the following:

  • Find / match records with dates between the presented range
  • Group results by day
  • Daily Average Returns

Here is my model, there are some useful properties to make this request easier, like the day property ...

 // Model var PriceHourlySchema = new Schema({ created: { type: Date, default: Date.now }, day: { type: String, required: true, trim: true }, hour: { type: String, required: true, trim: true }, price: { type: Number, required: true }, date: { type: Date, required: true } }, { autoIndex: true }); 

Here is my request so far, it only returns the Total Average for all dates in the range, and does not group by day and returns the average values ​​for each day, so you can $ group by day ...

 var start = moment.utc(req.query.start).startOf('year').toDate(); var end = moment.utc(req.query.start).add('years',1).startOf('year').add('hours',1).toDate(); PriceHourly.aggregate([ { $match: { date: { $gt: start, $lt: end } } }, { $group: { _id: null, price: { $avg: '$price' } } } ], function(err, results){ console.log(results); }); // PriceHourly(); 
+8
javascript mongodb mongoose express
source share
1 answer

The problem is with the _id you are using for $ group. You must group $day , not null , if you want to group the results by day. Try the following:

 PriceHourly.aggregate([ { $match: { date: { $gt: start, $lt: end } } }, { $group: { _id: "$day", price: { $avg: '$price' } } } ], function(err, results){ console.log(results); }); 

However, you do not need to store the day and hour as separate elements in the document. This is redundant data. You can extract the day and hour fields from date in an aggregation request using Date Aggregation statements.

+8
source share

All Articles