使用 mongodb 计算查找的总成本
Calculate total cost from lookup with 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();
我需要通过将价格乘以商品数据中的数量来计算价格...有什么想法可以做什么?
谢谢
你可以通过几种不同的方式实现这一点,我觉得最直接的做法是 $unwind
购物车的项目字段,进行计算然后恢复结构,如下所示:
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,
}
}
])
我有一个购物车,我正在尝试计算总费用,但我尝试的所有方法似乎都不起作用:
示例篮子集合:
{
"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
购物车的项目字段,进行计算然后恢复结构,如下所示:
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,
}
}
])