Home > Software engineering >  Mongodb filter query if sum of the array is greater than X
Mongodb filter query if sum of the array is greater than X

Time:12-27

I am trying to find sum of the array fields and after that, want to filter these sums are greater than 100.

{
  name: 'John',
  grades: [60, 70, 40]     # sum of this array = 170 (take this)
},
{
  name: 'Doe',
  grades: [30, 20, 10]     # sum of this array = 60 (don't take this)
}

I made the projection of this collection like this:

db.collections.find({}, {
{
  sumOfGrades: { $sum: "$grades" }
})

// returns

{...sumOfGrades: 170}, {...sumOfGrades: 60}

// But I am trying to get the first doc(which is greater than 100) on mongoDB layer.

CodePudding user response:

Query

  • you can do it with aggregation in easy way
  • sum the grades, and only those > 100 pass the match

*the filter is to keep or not document, project is to keep or not part of the document in general

Test code here

aggregate([{"$match":{"$expr":{"$gt":[{"$sum":"$grades"}, 100]}}}])
  • Related