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

如何在MongoDB查询的product数组中添加quantity字段?

解决方案

修改后的聚合查询如下,核心是保留并整合quantity字段到商品结构中:

Order.aggregate([
    // 关联用户集合获取用户详情
    { 
        $lookup: {  
            from: 'users',
            localField: 'user',
            foreignField: '_id',
            as: 'user'
        }
    },
    // 展开订单商品数组,便于逐个处理每个商品项
    { $unwind: '$orderItems' },
    // 关联商品集合获取对应商品详情
    {
        $lookup: {
            from: 'products', 
            localField: 'orderItems.product', 
            foreignField: '_id', 
            as: 'product'
        }
    },
    // 展开lookup返回的商品数组(因lookup默认返回数组)
    { $unwind: '$product' },
    // 构造目标格式的商品项:将商品详情包装为productId,同时带上数量
    {
        $project: {
            user: 1,
            productItem: {
                productId: '$product',
                quantity: '$orderItems.quantity',
                _id: '$orderItems._id' // 若orderItems无_id字段可删除此行
            }
        }
    },
    // 按订单ID分组,聚合用户信息和商品数组
    { 
        $group: { 
            _id: '$_id', 
            user: { $first: '$user' },
            products: { $push: '$productItem' }
        }
    }
])

核心调整说明:

  1. 移除quantity排除逻辑:原查询中$project: { quantity: 0 }会丢失订单商品的数量信息,直接删除该步骤以保留orderItems.quantity。
  2. 构造目标商品结构:新增$project步骤,将关联到的商品详情映射为productId字段,同时把数量和订单商品的_id(若存在)整合到同一个对象中,匹配你需要的输出格式。
  3. 聚合完整商品对象:分组时不再仅推送单纯的商品详情,而是推送构造好的包含数量的productItem对象,最终生成包含数量的商品数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:28:21