0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.