繁体   English   中英

MongoDB - 带条件的总和聚合

[英]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阶段应如下所示:

  1. $month - 从createdAt中获取月份值。
  2. $eq - 比较 (1) 中的月份和输入月份是否相同。
{
  $match: {
    $expr: {
      $eq: [
        {
          "$month": "$createdAt"
        },
        thisMonth.getMonth() + 1
      ]
    }
  }
}

示例 Mongo 游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM