简体   繁体   English

MongoDB聚合查询$ match不返回日期范围,为什么?

[英]MongoDB Aggregation Query $match returns nothing with date range, why?

I can't get the following MongoDB aggregation query to return a result. 我无法获得以下MongoDB聚合查询来返回结果。 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... 但是,当我执行PriceHourly.find({ date: { $lt: end, $gt: start }}) ,记录将按预期返回...

    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. MongoDB聚合框架的$ match不理解我提交的Moment Date对象。 $match appears to only work with native Javascript date objects. $ match似乎仅适用于本地Javascript日期对象。 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: 因此,如果您仍然想将Moment.js与$ match一起使用,只需使用Moment的toDate()方法将Moment.js日期对象转换为本机Javascript日期对象,如下所示:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM