node.js - 使用 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
购物车的 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,
}
}
])
推荐阅读
- python - 在python中使用正则表达式获取多个重复行
- mysql - hibernate.ddl.auto=更新创建 DDL 错误 CommandAcceptanceException
- vb.net-2010 - 如何修复 UPDATE 语句中的语法错误
- python - 使用python-telegram-bot按下开始时如何使用内联键盘发送gif?
- c# - 如何在 ASP.NET MVC 视图中解析 JSON 字符串
- javascript - Firebase CloudFirestore 参考数据类型
- firebase - Fluter-FutureBuilder-未获取AsyncSnapshot数据
- ios - 如何使用 API 中的数据搜索 tableview?
- c# - 检查数据是否存在后如何从数据库中获取数据
- node.js - 通过 npm 在 windows 中升级到最新的节点版本