develoguz
develoguz

Reputation: 13

Mongodb filter query if sum of the array is greater than X

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.

Upvotes: 0

Views: 642

Answers (1)

Takis
Takis

Reputation: 8705

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

Upvotes: 1

Related Questions