时间区间的操作:mongoose的aggregate无法match,但是find却可以找到。(非ObjecetID)
发布于 10 年前 作者 Hijiao 5729 次浏览 最后一次编辑是 9 年前 来自 问答
var getCustomerSourceListFromDataToData = function (accountid, startDate, endDate, callback) {
if (!startDate) {//启始时间默认30天前
    startDate = moment().subtract(30, 'days').format('L');
}
else {
    startDate = moment(startDate).format('L');
}
if (!endDate) {//结束时间默认今天
    endDate = moment().add(1, 'days').format('L');
} else {
    endDate = moment(endDate).add(1, 'days').format('L');
}
console.log('enddate:' + endDate);
console.log('startDate:' + startDate);
//CustomerSourceModel
//    .find({
//        date: {
//            $gte: startDate,
//            $lt: endDate
//        }
//    }).exec(callback);

CustomerSourceModel
    .aggregate()
    .match({
        date: {
            $gte: startDate,
            $lt: endDate
        }
    })
		.group({
       		 _id: null,
        	totalNum: {$sum: "$num"},
    })
    .exec(callback);
 }

如上代码,实现简单的时间区间内的统计数据,结果总是match不到相应的数据,用注释掉的find的代码可以找到相关数据,math却不可以。。 已经确认aggregate方法没问题,去掉match限制,就能统计数totalNum。

mongodb版本 3.04 先谢过大家了

2 回复

解决了,又是一个坑啊。是时间的格式写错了。 startDate = moment().subtract(30, ‘days’).format(‘L’);这时候时间是一个月前的时间,格式是2015-05-19. 在mongodb中直接查找db.customersources.find({‘date’:{$gte: ‘2015-05-19’ ) }})是查不出来任何符合条件的记录的。 图片20150618194515.png 使用db.customersources.find({‘date’:{$gte: new Date(2015-05-19 ) }})就可以查出来。 图片20150618194742.png

,至于为什么在mongoose中下列代码能查询出结果。。。

     CustomerSourceModel
    .find({
        date: {
         $gte: '2015-05-19'
      }
   }).exec(callback);

由于自己看不懂源代码,只能归因于mongoose太任性了吧~

最后将时间格式改成如下形式,看起来好蹩脚,不知道各位是如何设置的

if (!startDate) {//启始时间默认30天前
    startDate = moment(moment().subtract(30, 'days').format('L')).toDate();
}
else {
    startDate = moment(moment(startDate).format('L')).toDate();
}
if (!endDate) {//结束时间默认今天
    endDate = moment(moment().add(1, 'days').format('L')).toDate();
} else {
    endDate = moment(moment(endDate).add(1, 'days').format('L')).toDate();
}
回到顶部