[英]Summation of an array of array of numbers
I would like to find a total based on two arrays pbd
and input
.我想根据两个数组pbd
和input
找到一个总数。 The pipeline should multiply the pbd.charge.sellRate
with the input.quantity
whenever the type and size matches.管道应乘以pbd.charge.sellRate
与input.quantity
每当类型和尺寸相匹配。 Also I would like to add all this together to get one grand total.此外,我想将所有这些加在一起得到一个总数。
The input would be输入将是
{
"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"
}
]
}
So far I've used two $map
operators somewhat like two for loops like this:到目前为止,我已经使用了两个$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
}
}
}
}
}
}
}
}
])
and the output I get is this我得到的输出是这个
{
"_id": ObjectId("5a934e000102030405000000"),
"grandTotal": [
[
2400,
0
],
[
0,
0
]
]
}
Now I want to add all this array of arrays to get one total.现在我想添加所有这些数组以获得一个总数。 A better solution to this problem would also be highly appreciated.对此问题的更好解决方案也将受到高度赞赏。
This is a part of quite a long aggregation pipeline with lots of other data so I would prefer to not unwind and group the data.这是包含大量其他数据的相当长的聚合管道的一部分,因此我宁愿不展开和分组数据。 Is there any other option?还有其他选择吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.