You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB聚合查询:按日期范围筛选销量最高的商品

需求:按销量排序最受欢迎商品并支持日期范围筛选

需求说明:统计商品总销量(依据cartItems.qty字段)并按销量排序,同时支持通过order.createdAt字段筛选指定日期范围内的订单数据。

现有订单数据

db={
  orders: [
    {
      "_id": "63f37d1ac3dff5dd6d8cd156",
      "cartItems": [
        {
          "qty": 1,
          "product": {
            "_id": "63515ad7d5f84ecbaac38f1e",
            "code": "1",
            "name": "Coca-Cola",
            "pricePerItem": 3,
            "group": "Milk"
          },
          "price": 3,
          "total": 3
        }
      ],
      "createdAt": "2023-02-20T14:00:58.683Z"
    },
    {
      "_id": "63f37cd9c3dff5dd6d8cd14b",
      "cartItems": [
        {
          "qty": 1,
          "product": {
            "_id": "63515aeed5f84ecbaac38f24",
            "code": "2",
            "name": "Fanta",
            "pricePerItem": 4,
            "group": "Drink"
          },
          "price": 4,
          "total": 4
        },
        {
          "qty": 2,
          "product": {
            "_id": "63515ad7d5f84ecbaac38f1e",
            "code": "1",
            "name": "Coca-Cola",
            "pricePerItem": 3,
            "group": "Milk"
          },
          "price": 3,
          "total": 6
        }
      ],
      "createdAt": "2023-02-20T13:59:53.555Z"
    }
  ]
}

解决方案(MongoDB聚合查询)

以下聚合管道可实现需求,其中$match阶段可根据需要调整日期范围:

db.orders.aggregate([
  // 可选:筛选指定日期范围的订单,示例为2023-02-20当天
  {
    $match: {
      createdAt: {
        $gte: ISODate("2023-02-20T00:00:00Z"),
        $lte: ISODate("2023-02-20T23:59:59Z")
      }
    }
  },
  // 将每个订单的cartItems拆分为单独文档
  { $unwind: "$cartItems" },
  // 按商品ID分组,统计总销量
  {
    $group: {
      _id: "$cartItems.product._id",
      productName: { $first: "$cartItems.product.name" },
      totalQty: { $sum: "$cartItems.qty" }
    }
  },
  // 按总销量降序排序
  { $sort: { totalQty: -1 } },
  // 投射为更友好的输出格式,包含排名
  {
    $project: {
      _id: 0,
      productName: 1,
      totalSales: "$totalQty",
      rank: { $rank: {} }
    }
  }
])

预期结果

执行上述查询后,将得到按销量降序排列的商品列表:

  • 可口可乐(Coca-Cola)总销量3,排名第1
  • 芬达(Fanta)总销量1,排名第2

内容的提问来源于stack exchange,提问作者vanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:46:14