[英]MongoDB - Sum aggregation with conditionals
我正在聚合以对Orders
object 执行一些分析,我想从上个月的每个订单中获取总价,以及本月的总价,我尝试传入$match
参数,并使用适当的时间条件但它没有聚合任何数据。 即使我使用相同的时间条件执行countDocuments
查询,我也会返回许多文档。
const totalThis = await Order.aggregate([
{
$match: {
// should cut the amount of orders off at the beginning of the current month
createdAt: { $gte: thisMonth.getMonth() + 1 },
},
},
{
$group: {
// using $group, _id has to be there or it doesnt
// return anything, though we dont need an _id
_id: null,
total: {
$sum: "$totalPrice",
},
},
},
]);
res.status(200).json({
lastMonth: lastMonthSales,
thisMonth: thisMonthSales,
totalSalesLast: totalLast,
totalSalesThis: totalThis,
});
在我的 Postman 请求中, lastMonth
返回 0,因此返回totalSalesLast
的数组为空是有意义的,但是thisMonth
返回 5 个文档,因此它应该可以工作。 显然,如果我删除$match
条件,它将聚合所有文档,但那是因为它正在处理所有文档而不是实际过滤。
要在特定月份查询带有createdAt
的文档,您的$match
阶段应如下所示:
$month
- 从createdAt
中获取月份值。$eq
- 比较 (1) 中的月份和输入月份是否相同。{
$match: {
$expr: {
$eq: [
{
"$month": "$createdAt"
},
thisMonth.getMonth() + 1
]
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.