Group with multiple fields and get the count of duplicate field values grouped together innMongoDB

To group documents with multiple fields and count duplicate combinations in MongoDB, use the aggregation framework with $project and $group stages. The $cond operator helps normalize field values for consistent grouping regardless of field order.

Syntax

db.collection.aggregate([
    {
        $project: {
            field1: { $cond: { if: condition, then: value1, else: value2 } },
            field2: { $cond: { if: condition, then: value1, else: value2 } }
        }
    },
    {
        $group: {
            _id: { field1: "$field1", field2: "$field2" },
            count: { $sum: 1 }
        }
    }
]);

Sample Data

db.demo536.insertMany([
    {"Name1": "Chris", "Name2": "David"},
    {"Name1": "David", "Name2": "Chris"},
    {"Name1": "Bob", "Name2": "Sam"},
    {"Name1": "Chris", "Name2": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8c843eef4dcbee04fbbc01"),
        ObjectId("5e8c843fef4dcbee04fbbc02"),
        ObjectId("5e8c843fef4dcbee04fbbc03"),
        ObjectId("5e8c843fef4dcbee04fbbc04")
    ]
}

Display the documents ?

db.demo536.find();
{ "_id" : ObjectId("5e8c843eef4dcbee04fbbc01"), "Name1" : "Chris", "Name2" : "David" }
{ "_id" : ObjectId("5e8c843fef4dcbee04fbbc02"), "Name1" : "David", "Name2" : "Chris" }
{ "_id" : ObjectId("5e8c843fef4dcbee04fbbc03"), "Name1" : "Bob", "Name2" : "Sam" }
{ "_id" : ObjectId("5e8c843fef4dcbee04fbbc04"), "Name1" : "Chris", "Name2" : "David" }

Example: Group and Count Duplicate Field Combinations

Group documents by normalized Name1 and Name2 values to count duplicate combinations ?

db.demo536.aggregate([
    {
        $project: {
            FirstName1: {
                $cond: { if: { $gte: ["$Name1", "$Name2"] }, then: "$Name2", else: "$Name1" }
            },
            FirstName2: {
                $cond: { if: { $lt: ["$Name1", "$Name2"] }, then: "$Name2", else: "$Name1" }
            }
        }
    },
    {
        $group: {
            _id: {
                Name1: "$FirstName1",
                Name2: "$FirstName2"
            },
            count: { $sum: 1 }
        }
    }
]);
{ "_id" : { "Name1" : "Bob", "Name2" : "Sam" }, "count" : 1 }
{ "_id" : { "Name1" : "Chris", "Name2" : "David" }, "count" : 3 }

How It Works

  • $project stage: Uses $cond to normalize field order − ensures "Chris,David" and "David,Chris" are treated as the same combination
  • $group stage: Groups by the normalized field values and counts occurrences using $sum: 1
  • Result: Shows "Chris,David" appears 3 times (including the "David,Chris" variant)

Conclusion

Use MongoDB aggregation with $cond in $project to normalize field combinations, then $group to count duplicates. This approach treats different field orders as the same combination for accurate duplicate counting.

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

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements