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
CodePudding user response:
You can do followings in an aggregation pipeline:
$zip
to generate array of pairs fromR
andD
$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]
Here is the Mongo playground for your reference.