如何使用MongoDB聚合统计所有文档三级嵌套数组对象的quantity值总和
Mongoose 聚合实现库存按维度求和方案
核心思路
需要依次展开多层嵌套数组后,按指定维度分组对库存数量求和,具体实现如下:
聚合代码示例
const inventoryStats = await Products.aggregate([ // 展开产品变体数组 { $unwind: "$product_variants" }, // 展开单变体下的多规格数组 { $unwind: "$product_variants.variant_details" }, // 展开单规格下的多分门店库存数组 { $unwind: "$product_variants.variant_details.inventory" }, // 按「产品+变体+规格」维度分组,求和总库存 { $group: { _id: { product_id: "$_id", product_code: "$product_code", variant_code: "$product_variants.variant_code", variant_title: "$product_variants.variant_title", size: "$product_variants.variant_details.size" }, total_quantity: { $sum: "$product_variants.variant_details.inventory.quantity" } } }, // 可选:调整输出字段格式,简化返回结果 { $project: { _id: 0, product_id: "$_id.product_id", product_code: "$_id.product_code", variant_code: "$_id.variant_code", variant_title: "$_id.variant_title", size: "$_id.size", total_quantity: 1 } } ])
可选扩展
如果需要仅统计状态为Active的变体库存,可以在所有$unwind阶段之后新增$match过滤:
{ $match: { "product_variants.status": "Active" } }
如果不需要保留产品维度的关联信息,可直接删除$group._id中对应产品字段即可。
内容的提问来源于stack exchange,提问作者Ahnaf Ahmed
相关产品推荐
相关产品推荐

