I can't get the following MongoDB aggregation query to return a result. It only returns an empty array. I believe it's because it's not processing the date range correctly. However, when I do PriceHourly.find({ date: { $lt: end, $gt: start }})
the records are returned as expected...
var start = moment.utc('03-02-2012').startOf('day');
var end = moment.utc('03-02-2012').add('days',1).startOf('day');
PriceHourly.aggregate([
{ $match: { date: { $gt: start, $lt: end } } },
{ $group: { _id: null, avgPrice: { $avg: '$price' } } }
], function(err, results){
console.log(err, results);
});
// Model
var PriceHourlySchema = new Schema({
created: {
type: Date,
default: Date.now
},
full_date: {
type: String,
required: true,
trim: true
},
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
});
MongoDB Aggregation Framework's $match did not understand the Moment Date objects I submitted. $match appears to only work with native Javascript date objects. So, if you'd still like to use Moment.js with $match, simply convert the Moment.js Date Objects to Native Javascript Date Objects using Moment's toDate()
method, like this:
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.