Home > OS >  Calculations in MongoDB
Calculations in MongoDB

Time:09-28

I have something like:

    [
{
    ....
    a: 100
    b: 60
},
{
    ....
    a: 130
    b: 40
},
{
    ....
    a: 120
    b: 60
}
]

and I want to compute: sum(a)/sum(b): (350/160) and put it in a new field Thanks in advance

CodePudding user response:

First you should use $group to get sum of all a and b (group by _id:1), then use $project to get a/b (Mongo Playground):

db.collection.aggregate([
  {
    "$group": {
      "_id": 1,
      "sumA": {
        "$sum": "$a"
      },
      "sumB": {
        "$sum": "$b"
      },
      
    }
  },
  {
    "$project": {
      "aDIVb": {
        "$divide": [
          "$sumA",
          "$sumB"
        ]
      }
    }
  }
])

References: $group, $sum, $project and $divide

  • Related