Home > OS >  mongodb get values from array 2 based on indices from array 1
mongodb get values from array 2 based on indices from array 1

Time:10-14

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:

  1. $zip to generate array of pairs from R and D
  2. $filter to filter out pairs which R < 9; access the value of R in the pair by $arrayElemAt : [<pair>, 0]
  3. $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.

  • Related