Exploring MongoDB Aggregation Framework: Analyzing Student Exam Scores

in blurt •  last year 

Introduction:

This blog article will examine the MongoDB Aggregation Framework in depth and see how exam results can be analyzed using it. We'll go through the code step-by-step and explain each aggregate pipeline stage as we go. Using the offered code examples, you can see how to unwind arrays, filter and sort data, compute final scores, assign grades, and compute group and averages. Let's get going!

image.png
src

Code breakdown: The given code uses the aggregation pipeline of MongoDB to carry out a number of actions on the collection "students." We will segment the code and describe each step in the aggregate pipeline.

  1. Unwind and Match:
{ $unwind: "$scores" },
{ $match: { "scores.type": "exam" } }

The first step involves producing a new document for each array element by unwinding the "scores" array field in each page. The papers are only included in the second step if "scores.type" equals "exam."

  1. Add Project and Fields:
{
    $addFields: {
        "examFinalScore": {
            $round: ["$scores.score", 2]
        }
    }
},
{
    $project: {
        name: 1, examFinalScore: 1
    }
}

In this part, we round the "scores.score" field to two decimal places and add a new field named "examFinalScore" to each document. Then, for additional processing, we just project the "name" and "examFinalScore" columns.

src

  1. Fields to Add and Grade Assignment:-
{
    $addFields: {
        "grade": {
            $switch: {
                branches: [
                    { case: { $lt: ["$examFinalScore", 40] }, then: "F" },
                    { case: { $lt: ["$examFinalScore", 50] }, then: "D" },
                    { case: { $lt: ["$examFinalScore", 60] }, then: "C" },
                    { case: { $lt: ["$examFinalScore", 70] }, then: "B" },
                    { case: { $lt: ["$examFinalScore", 90] }, then: "A" },
                    { case: { $gte: ["$examFinalScore", 90] }, then: "A+" }
                ],
                default: ""
            }
        }
    }
}

Using the $switch operator, this part uses the "examFinalScore" to grade each document. To find the proper grade, the criteria are stated using the $lt (less than) and $gte (greater than or equal to) operators.

src

  1. Match and Sort:
{ $sort: { examFinalScore: -1 } },
{ $match: { grade: "A+" } }

Here, we sort the documents in descending order based on "examFinalScore" and then filter the documents to include only those with a grade of "A+".

  1. Group and Average Calculation:
{
    $group: {
        _id: null,
        average: { $avg: {$round:"$examFinalScore"} }
    }
}

The average of "examFinalScore" is determined in this section by aggregating all the papers and applying the $avg operator. The outcome is entered in the "average" field, which stands for the typical exam score.

  1. Disk use and performance enhancement:
}, { allowDiskUse: true });

The final section is an option passed to the aggregation pipeline, allowing MongoDB to use the disk for storing temporary data if the pipeline exceeds the system's available memory. This helps optimize performance for large datasets.

Conclusion:
In this blog post, we explored a MongoDB Aggregation Framework code example for analyzing student exam scores. We learned how to unwind arrays, filter and sort data, calculate final scores, assign grades, and perform group and average calculations. The Aggregation Framework provides a powerful set of tools for data analysis and manipulation in MongoDB, enabling developers to perform complex operations efficiently. Understanding these concepts is essential for leveraging MongoDB's capabilities to gain valuable insights from data.

src
full code:-

db.students.aggregate([
    { $unwind: "$scores" },
    { $match: { "scores.type": "exam" } },
    {
        $addFields: {
            "examFinalScore": {
                $round: ["$scores.score", 2]
            }
        }
    },
    {
        $project: {
            name: 1, examFinalScore: 1
        }
    },
    {
        $addFields: {
            "grade": {
                $switch: {
                    branches: [
                        {
                            case: { $lt: ["$examFinalScore", 40] },
                            then: "F"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 50] },
                            then: "D"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 60] },
                            then: "C"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 70] },
                            then: "B"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 90] },
                            then: "A"
                        },
                        {
                            case: { $gte: ["$examFinalScore", 90] },
                            then: "A+"
                        }
                    ],
                    default: ""
                }
            }
        }
    },
    { $sort: { examFinalScore: -1 } },
    {$match: {grade:"A+"}},
    {$out: "A_plus_pawa_polapans"}
]);


db.students.aggregate([
    { $unwind: "$scores" },
    { $match: { "scores.type": "exam" } },
    {
        $addFields: {
            "examFinalScore": {
                $round: ["$scores.score", 2]
            }
        }
    },
    {
        $project: {
            name: 1, examFinalScore: 1
        }
    },
    {
        $addFields: {
            "grade": {
                $switch: {
                    branches: [
                        {
                            case: { $lt: ["$examFinalScore", 40] },
                            then: "F"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 50] },
                            then: "D"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 60] },
                            then: "C"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 70] },
                            then: "B"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 90] },
                            then: "A"
                        },
                        {
                            case: { $gte: ["$examFinalScore", 90] },
                            then: "A+"
                        }
                    ],
                    default: ""
                }
            }
        }
    },
    { $sort: { examFinalScore: -1 } },
    { $match: { grade: "A+" } },
    {
        $group: {
            _id: null,
            average: { $avg: {$round:"$examFinalScore"} }
        }
    }
]);

db.students.aggregate([
    { $unwind: "$scores" },
    { $match: { "scores.type": "exam" } },
    {
        $addFields: {
            "examFinalScore": {
                $round: ["$scores.score", 2]
            }
        }
    },
    {
        $project: {
            name: 1, examFinalScore: 1
        }
    },
    {
        $addFields: {
            "grade": {
                $switch: {
                    branches: [
                        {
                            case: { $lt: ["$examFinalScore", 40] },
                            then: "F"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 50] },
                            then: "D"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 60] },
                            then: "C"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 70] },
                            then: "B"
                        },
                        {
                            case: { $lt: ["$examFinalScore", 90] },
                            then: "A"
                        },
                        {
                            case: { $gte: ["$examFinalScore", 90] },
                            then: "A+"
                        }
                    ],
                    default: ""
                }
            }
        }
    },
    { $sort: { examFinalScore: -1 } },
    {
        $setWindowFields: {
            sortBy: { examFinalScore: -1 },
            output: {
                position: { $rank: {} }
            }
        }
    }, {
        $setWindowFields: {
            sortBy: { examFinalScore: -1 },
            output: {
                position: { $rank: {} }
            }
        }
    },
], {
    allowDiskUse: true
});

db.students.aggregate([
    { $match: { "scores.type": "exam" } },
    { $project: { "scores": 1 } },
    {
        $addFields: {
            "scores": {
                $filter: {
                    input: "$scores",
                    as: "score",
                    cond: { $eq: ["$$score.type", "exam"] }
                }
            }
        }
    },
    { $unwind: "$scores" },
    { $sort: { "scores.score": -1 } },
    {
        $group: {
            _id: "$_id",
            scores: {
                $push: {
                    type: "$scores.type",
                    score: { $round: ["$scores.score", 2] }
                }
            }
        }
    },
    { $project: { "_id": 1, "scores": 1 } },
    { $match: { "scores.type": "exam", "scores.score": { $gte: 95 } } },
    { $sort: { "scores.score": -1 } }
]);
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!