首页 > 解决方案 > 使用 mongodb 从查找中计算总成本

问题描述

我有一个购物车,我正在尝试计算总成本,但我尝试的所有方法似乎都不起作用:

示例篮子集合:

{
    "hash": "xxxxx",
    "items": [
        {
            productCode: 'xxx',
            qty: 4
        }
    ]
}

示例产品集合:

{
   [
       {
           productCode: 'xxx',
           price: 299
       }
   ]
}

我当前的代码:

const basket = await this.collection.aggregate([
    { $match: { hash } }, // Find the shopping cart with the hash
    { $lookup: { from: 'products', localField: 'items.productCode', foreignField: 'productCode', as: 'products' } },
    { $limit: 1 },
    { $project: {
            _id: false,
            qtys: '$items',
            products: '$products'
            // totalCost // Output the total cost of all the products
        }
    }
]).toArray();

我需要通过将价格乘以项目数据中的数量来计算价格......关于做什么的任何想法?

谢谢

标签: node.jsmongodbe-commerce

解决方案


您可以通过几种不同的方式实现这一点,我觉得最直接的做法是对$unwind购物车的 item 字段进行计算,然后恢复结构,如下所示:

db.basket.aggregate([
  { $match: { hash } },
  {
    $limit: 1 // why do we need this? isn't the hash unique?
  },
  {
    $unwind: "$items"
  },
  {
    $lookup: {
      from: "products",
      localField: "items.productCode",
      foreignField: "productCode",
      as: "products"
    }
  },
  {
    $unwind: "$products"
  },
  {
    $group: {
      _id: "$_id",
      items: {
        $push: "$items"
      },
      products: {
        $push: "$products"
      },
      totalCost: {
        $sum: {
          "$multiply": [
            "$products.price",
            "$items.qty"
          ]
        }
      }
    }
  },
  {
    $project: {
      _id: false,
      
    }
  }
])

Mongo游乐场


推荐阅读