R2D2
R2D2

Reputation: 10737

mongodb get values from array 2 based on indices from array 1

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

Answers (1)

ray
ray

Reputation: 15287

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]
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

Related Questions