Group all documents with common fields in MongoDB?

To group all documents with common fields in MongoDB, use the $group aggregation stage with $addToSet operator. This accumulates unique values from documents that share the same field value.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: "$fieldToGroupBy",
            "groupedField": { $addToSet: "$fieldToAccumulate" }
        }
    }
]);

Sample Data

db.findDocumentWithCommonFieldsDemo.insertMany([
    { "UserId": 1, "UserName": "Carol" },
    { "UserId": 2, "UserName": "David" },
    { "UserId": 1, "UserName": "Sam" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cdf8ebebf3115999ed51200"),
        ObjectId("5cdf8ebebf3115999ed51201"),
        ObjectId("5cdf8ebebf3115999ed51202")
    ]
}

View Sample Data

db.findDocumentWithCommonFieldsDemo.find();
{ "_id": ObjectId("5cdf8ebebf3115999ed51200"), "UserId": 1, "UserName": "Carol" }
{ "_id": ObjectId("5cdf8ebebf3115999ed51201"), "UserId": 2, "UserName": "David" }
{ "_id": ObjectId("5cdf8ebebf3115999ed51202"), "UserId": 1, "UserName": "Sam" }

Group Documents by Common Fields

Group all documents by UserId and collect unique UserName values ?

db.findDocumentWithCommonFieldsDemo.aggregate([
    {
        $group: {
            _id: "$UserId",
            "UserDetails": { $addToSet: "$UserName" }
        }
    }
]);
{ "_id": 2, "UserDetails": [ "David" ] }
{ "_id": 1, "UserDetails": [ "Sam", "Carol" ] }

Key Points

  • $group groups documents by the specified field (_id field in the group stage).
  • $addToSet creates an array of unique values from the grouped documents.
  • Documents with UserId: 1 are grouped together with their unique UserName values.

Conclusion

Use $group with $addToSet to efficiently group documents by common field values and accumulate unique data from those groups. This approach eliminates duplicates while preserving all distinct values.

Updated on: 2026-03-15T01:28:56+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements