0

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.

1 Answer 1

1

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