Getting a list of values by using MongoDB $group?

To get a list of values using MongoDB, use the $group aggregation stage along with the $push operator. This approach groups documents by a specific field and creates an array of values from another field.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: "$groupingField",
            arrayField: { $push: "$fieldToCollect" }
        }
    }
]);

Sample Data

First, let's create a collection with sample documents ?

db.groupByDemo.insertMany([
    { "UserName": "John", "Subject": "MongoDB" },
    { "UserName": "Larry", "Subject": "MySQL" },
    { "UserName": "John", "Subject": "Java" },
    { "UserName": "John", "Subject": "C" },
    { "UserName": "Larry", "Subject": "SQL Server" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd69f0457806ebf1256f136"),
        ObjectId("5cd69f0657806ebf1256f137"),
        ObjectId("5cd69f0d57806ebf1256f138"),
        ObjectId("5cd69f1357806ebf1256f139"),
        ObjectId("5cd69f1c57806ebf1256f13a")
    ]
}

Let's view all documents in the collection ?

db.groupByDemo.find().pretty();
{
    "_id": ObjectId("5cd69f0457806ebf1256f136"),
    "UserName": "John",
    "Subject": "MongoDB"
}
{
    "_id": ObjectId("5cd69f0657806ebf1256f137"),
    "UserName": "Larry",
    "Subject": "MySQL"
}
{
    "_id": ObjectId("5cd69f0d57806ebf1256f138"),
    "UserName": "John",
    "Subject": "Java"
}
{
    "_id": ObjectId("5cd69f1357806ebf1256f139"),
    "UserName": "John",
    "Subject": "C"
}
{
    "_id": ObjectId("5cd69f1c57806ebf1256f13a"),
    "UserName": "Larry",
    "Subject": "SQL Server"
}

Example: Group Subjects by UserName

Now let's group documents by UserName and collect all subjects for each user ?

db.groupByDemo.aggregate([
    {
        $group: {
            "_id": "$UserName",
            "Subject": { $push: "$Subject" }
        }
    }
]);
{ "_id": "Larry", "Subject": [ "MySQL", "SQL Server" ] }
{ "_id": "John", "Subject": [ "MongoDB", "Java", "C" ] }

Key Points

  • $group aggregates documents by the field specified in _id
  • $push creates an array by collecting values from the specified field
  • The result shows each unique UserName with an array of all their subjects

Conclusion

The combination of $group and $push efficiently creates lists of values grouped by a common field. This technique is particularly useful for collecting related data points under shared identifiers.

Updated on: 2026-03-15T01:16:46+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements