MongoDB query for counting number of unique fields grouped by another field?

To count the number of unique field combinations grouped by another field in MongoDB, use the aggregation pipeline with $group stages. First group by the unique combinations, then group again by the target field to count occurrences.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: {
                "groupField": "$groupField",
                "uniqueField": "$uniqueField"
            }
        }
    },
    {
        $group: {
            _id: "$_id.groupField",
            "count": { $sum: 1 }
        }
    }
]);

Sample Data

db.demo354.insertMany([
    {"Name1": "Chris", "Name2": "David"},
    {"Name1": "Chris", "Name2": "David"},
    {"Name1": "Chris", "Name2": "Bob"},
    {"Name1": "Carol", "Name2": "John"},
    {"Name1": "Carol", "Name2": "John"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("..."),
        ObjectId("...")
    ]
}

Display Sample Data

db.demo354.find();
{ "_id": ObjectId("5e5685a6f8647eb59e5620c0"), "Name1": "Chris", "Name2": "David" }
{ "_id": ObjectId("5e5685a9f8647eb59e5620c1"), "Name1": "Chris", "Name2": "David" }
{ "_id": ObjectId("5e5685aff8647eb59e5620c2"), "Name1": "Chris", "Name2": "Bob" }
{ "_id": ObjectId("5e5685c4f8647eb59e5620c3"), "Name1": "Carol", "Name2": "John" }
{ "_id": ObjectId("5e5685c5f8647eb59e5620c4"), "Name1": "Carol", "Name2": "John" }

Example: Count Unique Name2 Values by Name1

db.demo354.aggregate([
    {
        $group: {
            _id: {
                "Name1": "$Name1",
                "Name2": "$Name2"
            }
        }
    },
    {
        $group: {
            _id: "$_id.Name1",
            "uniqueCount": { $sum: 1 }
        }
    },
    {
        $project: {
            _id: 0,
            Name1: "$_id",
            uniqueCount: 1
        }
    }
]);
{ "uniqueCount": 2, "Name1": "Chris" }
{ "uniqueCount": 1, "Name1": "Carol" }

How It Works

  • Stage 1: Group by both fields to create unique combinations
  • Stage 2: Group by the target field and count unique combinations with $sum: 1
  • Stage 3: Project to format the output with readable field names

Conclusion

Use a two-stage aggregation pipeline to count unique field combinations. The first $group creates unique pairs, and the second counts them by the grouping field.

Updated on: 2026-03-15T02:35:53+05:30

381 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements