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); });
ac360
source share