MongoDB query to implement aggregate function

MongoDB aggregate functions allow you to perform data processing operations on collections, such as filtering, grouping, and transforming documents. The aggregation pipeline processes documents through multiple stages to produce computed results.

Syntax

db.collection.aggregate([
    { $match: { field: value } },
    { $unwind: "$arrayField" },
    { $group: { _id: "$field", operation: { $operator: expression } } }
])

Sample Data

Let us first create a collection with documents ?

db.demo121.insertOne({
    "Id": 101,
    "Details": [
        {
            "SubjectId": "1",
            "SubjectName": "MongoDB",
            "Score": 76
        },
        {
            "SubjectId": "2",
            "SubjectName": "MySQL",
            "Score": 76
        },
        {
            "SubjectId": "3",
            "SubjectName": "Java",
            "Score": 76
        }
    ]
})
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2f1c60140daf4c2a3544b3")
}

Display all documents from the collection ?

db.demo121.find()
{
    "_id": ObjectId("5e2f1c60140daf4c2a3544b3"),
    "Id": 101,
    "Details": [
        { "SubjectId": "1", "SubjectName": "MongoDB", "Score": 76 },
        { "SubjectId": "2", "SubjectName": "MySQL", "Score": 76 },
        { "SubjectId": "3", "SubjectName": "Java", "Score": 76 }
    ]
}

Example: Aggregation Pipeline

The following query implements an aggregation function to process and group the nested array data ?

db.demo121.aggregate([
    { "$match": { "Id": 101 } },
    { "$unwind": "$Details" },
    {
        "$group": {
            "_id": "$Details.SubjectId",
            "count": { "$sum": 1 },
            "Details": {
                "$push": {
                    "SubjectName": "$Details.SubjectName"
                }
            }
        }
    },
    {
        "$group": {
            "_id": null,
            "List": {
                "$push": {
                    "SubId": "$_id",
                    "Details": "$Details"
                }
            }
        }
    }
])
{
    "_id": null,
    "List": [
        { "SubId": "3", "Details": [ { "SubjectName": "Java" } ] },
        { "SubId": "2", "Details": [ { "SubjectName": "MySQL" } ] },
        { "SubId": "1", "Details": [ { "SubjectName": "MongoDB" } ] }
    ]
}

How It Works

  • $match: Filters documents where Id equals 101
  • $unwind: Separates each array element into individual documents
  • $group (first): Groups by SubjectId and counts occurrences
  • $group (second): Combines all groups into a single result array

Conclusion

MongoDB aggregation pipelines provide powerful data processing capabilities through multiple stages. The combination of $match, $unwind, and $group operators enables complex transformations of nested array data into structured results.

Updated on: 2026-03-15T02:11:18+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements