[英]mongoDB: mongoose vs command line aggregation
我正在尝试使用以下命令运行mongoDB聚合:
Procedures.aggregate(
{
$match : {
funded: true,
updatedate : { $gte : new Date(startOfMonth) }
}
},
{
$project: {
_id : 0,
amount: 1,
date : '$updatedate',
h: {$hour : '$updatedate'},
m: {$minute : '$updatedate'},
s: {$second : '$updatedate'},
ml: {$millisecond : '$updatedate'}
},
$project: {
_id: 0,
amount: 1,
date : {
$subtract : [
'$date',
{
$add: [
'$ml',
{$multiply : ['$s',1000]},
{$multiply : ['$m',60,1000]},
{$multiply : ['$h',60,60,1000]}
]
}
]
} // transform to simple date 01/01/2016
}
},
{
$group: {
_id: {
d: '$date'
},
total : {
$sum : "$amount"
},
count: { $sum: 1 }
}
},
function(err, data){
if (err) {
console.log("ERROR: DashboardModel::getDailyDataForMonth: " + err);
}
console.log(JSON.stringify(data));
return callback();
});
问题是当我使用命令行运行聚合时,该聚合工作正常:
db.procedures.aggregate([{$match : {funded: true,updatedate : { $gte : new Date('2016-01-01T08:00:00.000Z'), $lt: new Date('2016-01-31T08:00:00.000Z') }}}, { $project: {_id: 0, date: '$updatedate', amount: 1, h : {$hour : '$updatedate'},m : {$minute : '$updatedate'},s : {$second : '$updatedate'},ml : {$millisecond : '$updatedate'}} }, {$project: {_id: 0, amount: 1, date : {$subtract : ['$date',{ $add : ['$ml',{$multiply : ['$s',1000]},{$multiply : ['$m',60,1000]},{$multiply : ['$h',60,60,1000]}]}]}} }, { $group: {_id: {d: '$date' }, total: {$sum: "$amount"}, count: {$sum: 1}} }]
{ "_id" : { "d" : ISODate("2016-01-07T00:00:00Z") }, "total" : 389, "count" : 3 }
猫鼬回来的地方
[{"_id":{"d":null},"total":389,"count":3}]
我不确定自己在做什么错。
如果您只是想将日期转换为特定格式,请在$group
管道中使用$dateToString
运算符:
Procedures.aggregate(
{
"$match": {
"funded": true,
"updatedate": { "$gte" : new Date(startOfMonth) }
}
},
{
"$group": {
"_id": {
"yearMonthDay": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$updatedate"
}
}
},
"total": { "$sum": "$amount" },
"count": { "$sum": 1 }
}
},
function(err, data){
if (err) {
console.log("ERROR: DashboardModel::getDailyDataForMonth: " + err);
}
console.log(JSON.stringify(data));
return callback();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.