[英]MongoDB Aggregation Framework - How to Match by Date Range, Group By Days, and Return Average For Each Day?
我剛剛學習了MongoDB的聚合框架,我想知道是否有人可以幫助我改進此查詢以執行以下操作:
這是我的模型,有一些有用的屬性可以使這個查詢更容易,比如day
屬性......
// 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
});
這是我的查詢到目前為止,這只返回范圍內包含的所有日期的總平均值,並且不按天分組並返回每天的平均值,因此您可以按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();
問題似乎與你用於$ group的_id
有關。 如果要按$day
分組結果,則應按$day
分組而不是null
。 嘗試這個:
PriceHourly.aggregate([
{ $match: { date: { $gt: start, $lt: end } } },
{ $group: { _id: "$day", price: { $avg: '$price' } } }
], function(err, results){
console.log(results);
});
也就是說,您不需要將日期和小時存儲為文檔中的單獨元素。 這是冗余數據。 您可以提取的day
和hour
從date
字段使用聚合查詢Date Aggregation
運營商。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.