我怎样才能知道每个月卖出了多少产品?

How can I find out how many products were sold in each month?

我有一个产品系列,其结构如下:

{   _id: 01,
    user_id: 10,
    line_items: [
      { 
        _id: 2,
        quantity: 2,
      },
      { 
        _id: 3,
        quantity:  1,
      }
    ],
    purchase_date: 2021-02-05T21:00:00.000+00:00
  }

我怎样才能知道每个月卖出了多少产品?

选项 1 最简单快捷的是:

 db.collection.aggregate([
 {
   $group: {
     _id: {
       "$substr": [
         "$purchase_date",
         0,
         7
       ]
    },
     count: {
       $sum: 1
     }
   }
 }
])

解释:

按包含年份和月份的前 7 个字符分组:“2021-12”并计算产品数量。

playground1

选项 2:将字符串转换为 date/month:

db.collection.aggregate([
{
  $group: {
    _id: {
      $month: {
        $dateFromString: {
          dateString: "$purchase_date"
        }
      }
     },
     count: {
       $sum: 1
     }
   }
  }
 ])

解释:

将字符串转换为月和组

playground2

要找出每个月售出的订单项数量,您需要 运行 一个聚合,其中管道由表达式 [=16] 返回的数量数组 $group stage. The group by key will be the month value returned by the $month operator on the purchase_date field. The count will consist of the $sum operator on another $sum 组成=] 本质上被解释为上述文件

{ $sum: [2, 1] } => 3

因此您的整体流程如下:

db.collection.aggregate([
  { $group: {
      _id: {
        "$month": "$purchase_date"
      },
      total: {
        $sum: {
          $sum: "$line_items.quantity"
        }
      }
  } }
])

Mongo Playground