【发布时间】:2020-11-30 13:29:57
【问题描述】:
我在 MongoDB 中使用聚合按 $year、$month 和 $dayOfMonth 对字段进行分组。
Transaction.aggregate(
[{
$group: {
_id: {
year : { $year : "$createdAt" },
month : { $month : "$createdAt" },
day : { $dayOfMonth : "$createdAt" },
},
totalQuantity: {
$sum: "$totalQuantity"
},
totalAmount: {
$sum: "$totalAmount"
},
totalPayment: {
$sum: "$totalPayment"
},
count: { $sum: 1 }
}
}
]).then( res => console.log(res));
在上面的代码中,我使用了默认的 $createdAt 字段,但是当我尝试使用具有 Unix 时间戳的日期的 $date 时,它会引发错误。
我尝试了什么?
Transaction.aggregate(
[{
$group: {
_id: {
year : { $year : new Date("$date") },
month : { $month : new Date("$date") },
day : { $dayOfMonth : new Date("$date") },
},
totalQuantity: {
$sum: "$totalQuantity"
},
totalAmount: {
$sum: "$totalAmount"
},
totalPayment: {
$sum: "$totalPayment"
},
count: { $sum: 1 }
}
}
]).then( res => console.log(res));
但这不起作用,因为 "$date" 作为字符串传递给 Date 构造函数。有什么解决方法吗?
【问题讨论】: