I would like to find a total based on two arrays pbd and input.
The pipeline should multiply the pbd.charge.sellRate with the input.quantity whenever the type and size matches. 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:
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?