Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
mongoDB: perform collection.find() on calculated vales in documents

Say I have the following documents in a collection:

{
    "_id" : ObjectId("111e2133c57a1d6111111111"),
    "scores" : [ 
        {
            "date" : ISODate("2021-03-29T05:00:20.965Z"),
            "test 1 points" : 50,
            "test 2 points" : 10,
            "total possible points" : 100
        }
    ]
}

{
    "_id" : ObjectId("111e2133c57a1d6111111222"),
    "scores" : [ 
        {
            "date" : ISODate("2021-03-27T05:00:20.965Z"),
            "test 1 points" : 30,
            "test 2 points" : 20,
            "total possible points" : 200
        }
    ]
}

If I want to find all the documents which have ("test 1 points" + "test 2 points") / "total possible points" greater than .50, is there a way to do this efficiently with the MongoDB find() command?

Currently, I am using the inefficient method of looping through each document and performing my calculations, then recording the ObjectId if the calculated value is greater than .50.

Thanks in advance!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Demo - https://mongoplayground.net/p/c19Xx9-Ahb-

$unwind the scores to get into individual documents, use $add $divide with $gt to validEntry as true or false.

and $match documents back

db.collection.aggregate([
  { $unwind: "$scores" },
  {
    $addFields: {
      validEntry: {
        $gt: [
          { $divide: [
              { $add: [ "$scores.test 1 points", "$scores.test 2 points" ] },
              "$scores.total possible points"
            ]
          },
        0.5]
      }
    }
  },
  { $match: { validEntry: true } }
])

if you want to get the original document back $group them by _id and $push scores back to the array.

  {
    $group: { _id: "_id", scores: { $push: "$scores" } }
  }

https://mongoplayground.net/p/d8xhOHYV4kn

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!