Home > OS >  How to sum an array with different key index mongodb
How to sum an array with different key index mongodb

Time:02-05

Hello i'm having a problem to sum the field clicks, with different key values.

i have a collection like this:

"clicks": {
        "2022-02-03": 30,
        "2022-02-02": 50,
        "2022-02-01": 45,
        "2022-01-31": 40,
        "2022-01-30": 40,
        "2022-01-29": 50,
        "2022-01-28": 55,
        "2022-01-27": 50,
        "2022-01-26": 40,
        "2022-01-25": 30,
        "2022-01-24": 35,
        "2022-01-23": 33,
        "2022-01-22": 32,
        "2022-01-21": 30
    }

I would like a result like, sum just the numbers:

sum: 560

How can i sum with different index keys?

CodePudding user response:

playground

db.collection.aggregate([
  {
    $project: {
      "c": { //Since you have dynamic keys, reshape the data
        "$objectToArray": "$clicks"
      }
    }
  },
  {
    "$project": {
      "clicks": { //sum the value part of dynamic key
        "$sum": "$c.v"
      }
    }
  }
])
  •  Tags:  
  • Related