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

MongoDB关联Order与Products集合并按_id分组计算订单总金额

MongoDB关联查询实现订单金额与商品种类统计

以下聚合查询直接在Order集合上执行即可得到符合要求的输出:

db.Order.aggregate([
  // 关联Products集合获取商品单价信息
  {
    $lookup: {
      from: "Products",
      localField: "products.productId",
      foreignField: "_id",
      as: "productInfos"
    }
  },
  // 计算订单总金额与商品种类数
  {
    $project: {
      thanhtien: {
        $sum: {
          $map: {
            input: "$products",
            as: "orderItem",
            in: {
              $multiply: [
                "$$orderItem.quantity",
                {
                  $getField: {
                    input: {
                      $first: {
                        $filter: {
                          input: "$productInfos",
                          cond: { $eq: ["$$this._id", "$$orderItem.productId"] }
                        }
                      }
                    },
                    field: "price"
                  }
                }
              ]
            }
          }
        }
      },
      "Số mặt hàng đặt": { $size: "$products" }
    }
  },
  // 调整输出的_id结构匹配要求
  {
    $group: {
      _id: { _id: "$_id" },
      thanhtien: { $first: "$thanhtien" },
      "Số mặt hàng đặt": { $first: "$Số mặt hàng đặt" }
    }
  },
  // 按总金额降序排序,和示例输出顺序一致
  {
    $sort: { thanhtien: -1 }
  }
])

步骤说明

  • $lookup阶段:关联Products集合,拉取订单中所有商品的详细信息存入临时数组productInfos
  • $project阶段:遍历订单商品列表,匹配每个商品对应的单价,计算单类商品总价后求和得到订单总金额thanhtien,同时取订单商品数组长度得到商品种类数
  • $group阶段:按订单ID分组,调整输出的_id为嵌套格式,匹配需求的输出结构
  • $sort阶段:可选步骤,按总金额降序排序,运行后输出顺序与示例完全一致

内容的提问来源于stack exchange,提问作者Long Tran Hoang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:15:04