node.js - 数字数组数组的总和
问题描述
我想根据两个数组pbd
和input
. 只要类型和大小匹配,管道就应该将pbd.charge.sellRate
与相乘。input.quantity
此外,我想将所有这些加在一起以获得一个总计。
输入将是
{
"pbd": [
{
"type": "STD",
"size": "20",
"charge": {
"sellRate": 120
}
},
{
"containerType": "STD",
"containerSize": "40",
"charge": {
"sellRate": 290
}
}
],
"input": [
{
"type": "STD",
"size": "20",
"quantity": "20"
},
{
"type": "STD",
"size": "40",
"quantity": "20"
}
]
}
到目前为止,我已经使用了两个$map
运算符,有点像这样的两个 for 循环:
db.collection.aggregate([
{
$project: {
"grandTotal": {
$map: {
input: "$pbd",
as: "pbd",
in: {
$map: {
input: "$input",
as: "inp",
in: {
$cond: {
if: {
$and: [
{
$eq: [
"$$pbd.type",
"$$inp.type"
]
},
{
$eq: [
"$$pbd.size",
"$$inp.size"
]
}
]
},
then: {
$multiply: [
{
$toInt: "$$pbd.charge.sellRate"
},
{
$toInt: "$$inp.quantity"
}
]
},
else: 0
}
}
}
}
}
}
}
}
])
我得到的输出是这个
{
"_id": ObjectId("5a934e000102030405000000"),
"grandTotal": [
[
2400,
0
],
[
0,
0
]
]
}
现在我想添加所有这些数组以获得一个总数。对此问题的更好解决方案也将受到高度赞赏。
这是包含许多其他数据的相当长的聚合管道的一部分,因此我宁愿不展开和分组数据。还有其他选择吗?
解决方案
推荐阅读
- javascript - 在 react-konva 中更改 Hover 上的光标
- excel - 预期的变量或过程,而不是模块
- python - 如何对多个日期时间数据进行聚类以发现模式
- reactjs - 将排毒与 Fastlane 相结合
- sql - 使用连接的 SQL Server JSON 数组外键值
- ruby - 在我的本地主机 elasticsearch::Transport::Transport::Errors::NotAcceptable 上出现错误
- mysql - mysql:检查列ID是否连续
- javascript - 包含 laravel 页面时可以访问 vuejs v-model
- ruby - 如何在条件语句中存储一个值并在 ruby 中调用它
- doctrine - 从连接表中选择