我有一个购物车,我想算出总费用,但是我尝试的所有方法似乎都不起作用:
篮子收集示例:
{
"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();
我需要通过将价格乘以商品数据中的数量来得出价格...有关该怎么做的任何想法?
谢谢
您可以通过几种不同的方法来实现此目的,我觉得最直接的方法是对$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,
}
}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句