Select documents grouped by field in MongoDB?

To select documents grouped by field in MongoDB, use the $group stage in an aggregation pipeline along with $project to reshape the output. The $group stage groups documents by specified field values and accumulates data using operators like $push.

Syntax

db.collection.aggregate([
    {
        "$group": {
            "_id": { "field1": "$field1", "field2": "$field2" },
            "groupedData": { "$push": { "field3": "$field3" } }
        }
    },
    {
        "$project": {
            "_id": "$_id.field1",
            "field2": "$_id.field2",
            "groupedData": 1
        }
    }
]);

Sample Data

db.demo540.insertMany([
    { "id": 1, "Name": "Chris", "CountryName": "US" },
    { "id": 1, "Name": "Chris", "CountryName": "UK" },
    { "id": 1, "Name": "Chris", "CountryName": "AUS" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8ca368ef4dcbee04fbbc0e"),
        ObjectId("5e8ca36bef4dcbee04fbbc0f"),
        ObjectId("5e8ca370ef4dcbee04fbbc10")
    ]
}

View Sample Data

db.demo540.find();
{ "_id": ObjectId("5e8ca368ef4dcbee04fbbc0e"), "id": 1, "Name": "Chris", "CountryName": "US" }
{ "_id": ObjectId("5e8ca36bef4dcbee04fbbc0f"), "id": 1, "Name": "Chris", "CountryName": "UK" }
{ "_id": ObjectId("5e8ca370ef4dcbee04fbbc10"), "id": 1, "Name": "Chris", "CountryName": "AUS" }

Example: Group by ID and Name

Group documents by id and Name fields, collecting all CountryName values into an array ?

db.demo540.aggregate([
    {
        "$group": {
            "_id": {
                "id": "$id",
                "Name": "$Name"
            },
            "details": {
                "$push": {
                    "CountryName": "$CountryName"
                }
            }
        }
    },
    {
        "$project": {
            "_id": "$_id.id",
            "Name": "$_id.Name",
            "details": 1
        }
    }
]);
{
    "details": [
        { "CountryName": "US" },
        { "CountryName": "UK" },
        { "CountryName": "AUS" }
    ],
    "_id": 1,
    "Name": "Chris"
}

How It Works

  • $group groups documents by the _id field containing multiple grouping criteria
  • $push accumulates values from grouped documents into an array
  • $project reshapes the output by extracting grouped fields and renaming the _id

Conclusion

Use $group with $push to collect grouped documents into arrays, then $project to format the final output. This approach effectively groups documents by specified fields while preserving related data in structured arrays.

Updated on: 2026-03-15T03:30:48+05:30

514 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements