Reputation: 10737
My document:
{ R:[1, 10, 4, 6, 20] , D:[ 40, 70, 90, 100, 50] }
Arrays R & D are same size.
Problem:
Please find the sum of distances “D” for which the R is lower than 9?
Expected result:
Sum(D)=40+90+100=230
Upvotes: 0
Views: 37
Reputation: 15287
You can do followings in an aggregation pipeline:
$zip
to generate array of pairs from R
and D
$filter
to filter out pairs which R < 9; access the value of R in the pair by $arrayElemAt : [<pair>, 0]
$reduce
to sum the value of D of remaining elements; access the value of D in the pair by $arrayElemAt : [<pair>, 1]
db.collection.aggregate([
{
"$project": {
"zip": {
"$zip": {
"inputs": [
"$R",
"$D"
]
}
}
}
},
{
"$project": {
filtered: {
"$filter": {
"input": "$zip",
"as": "z",
"cond": {
"$lt": [
{
"$arrayElemAt": [
"$$z",
0
]
},
9
]
}
}
}
}
},
{
"$project": {
result: {
"$reduce": {
"input": "$filtered",
"initialValue": 0,
"in": {
$add: [
"$$value",
{
"$arrayElemAt": [
"$$this",
1
]
}
]
}
}
}
}
}
])
Here is the Mongo playground for your reference.
Upvotes: 1