前段時間遇到的問題,在cnode上求助https://cnodejs.org/topic/5582a4bb395a0c1812f183ea
最後自己解決了,詳情如下:
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
解決了,又是一個坑啊。是時間的格式寫錯了。
startDate = moment().subtract(30, ‘days’).format(‘L’);這時候時間是一個月前的時間,格式是2015-05-19.
在mongodb中直接查找db.customersources.find({’date’:{$gte: ‘2015-05-19’ ) }})是查不出來任何符合條件的記錄的。
使用db.customersources.find({’date’:{$gte: new Date(2015-05-19 ) }})就可以查出來。
至於爲什麼在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();
}