DEV Community

Judy
Judy

Posted on

2 1 1 1 1

How to Compute Arrays and Get Record Containing the Largest Value on a MongoDB Collection #80

The following collection contains a list table of nested structure. One computing scenario is to compute values in the list table and get records containing the largest value. Below is scores collection that stores student scores of a number of subjects. We are trying to get students obtaining the highest average score.

{
         "StudentID":"S0001",
           "Scores":[{"Course":"Chinese","Score":75},{"Course":"Maths","Score":81},
          {"Course":"English","Score":78}]
    }
    {
         "StudentID":"S0002",
           "Scores":[{"Course":"Chinese","Score":80},{"Course":"Maths","Score":78},
          {"Course":"English","Score":76}]
    }
    {
         "StudentID":"S0001",
         "Scores":[{"Course":"Chinese","Score":78},{"Course":"Maths","Score":75},
          {"Course":"English","Score":72}]
    }
Enter fullscreen mode Exit fullscreen mode

The MongoDB way of getting the task done is like this: use $unwind under aggregate to expand each Scores value into multiple rows, group the rows by StudentID and calculate the average score avg_score, group and sort records by avg_score, get records of student IDs having the highest average score, use  $unwind to expand each student ID, and finally, show the eligible records.

 It is convenient to perform the computing task using esProc SPL. It will return the eligible records according to the highest average score.

1. Write script scores.dfx in esProc:

Image description
2. Start debugging and execute the code. Below is the value of cell A2:

Image description

3. Execute the script and below is the value of A3:

Image description
You can alos use esProc SPL to sum scores of subjects and get the max or min value.

Read How to Call an SPL Script in Java to learn about the integration of an SPL script with a Java program.

Open source SPL source address

Download

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay