Search code examples
node.jsmongodbe-commerce

Calculate total cost from lookup with mongodb


I have a shopping cart, I am trying to work out the total cost but everything I try doesn't seem to work:

Example Basket Collection:

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

Example Products Collection:

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

My current code:

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();

I need to work out the price by multiplying it by the qty in the items data... any ideas on what to do?

Thank you


Solution

  • You can achieve this in several different ways, I feel the most straight forward to do this is to $unwind the item field of the cart, do the calculation and then restore the structure like so:

    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,
          
        }
      }
    ])
    

    MongoPlayground