Get distinct pair of objects with all subdocuments in MongoDB?

To get a distinct pair of objects with all subdocuments in MongoDB, use the $group aggregation operator to group documents by a specific field and aggregate their values. This technique helps combine duplicate entries into unique pairs with consolidated data.

Syntax

db.collection.aggregate([
    {
        $group: {
            _id: "$fieldToGroupBy",
            aggregatedField: { $operator: "$fieldToAggregate" }
        }
    },
    {
        $project: {
            newFieldName: "$_id",
            _id: 0,
            aggregatedField: 1
        }
    }
]);

Sample Data

db.demo522.insertMany([
    { "Name": "John", "Score": 45 },
    { "Name": "Bob", "Score": 67 },
    { "Name": "John", "Score": 55 },
    { "Name": "Bob", "Score": 33 }
]);

Display all documents from the collection ?

db.demo522.find();
{ "_id" : ObjectId("5e89b646b3fbf26334ef611b"), "Name" : "John", "Score" : 45 }
{ "_id" : ObjectId("5e89b64eb3fbf26334ef611c"), "Name" : "Bob", "Score" : 67 }
{ "_id" : ObjectId("5e89b655b3fbf26334ef611d"), "Name" : "John", "Score" : 55 }
{ "_id" : ObjectId("5e89b65cb3fbf26334ef611e"), "Name" : "Bob", "Score" : 33 }

Example: Group by Name and Sum Scores

Group documents by Name and calculate the total Score for each person ?

var query = [
    {
        $group: {
            _id: "$Name",
            Score: { $sum: "$Score" }
        }
    },
    {
        $project: {
            Name: "$_id", 
            _id: 0, 
            Score: 1
        }
    }
];

db.demo522.aggregate(query);
{ "Score" : 100, "Name" : "Bob" }
{ "Score" : 100, "Name" : "John" }

How It Works

  • $group groups documents by the Name field and sums all Score values for each name.
  • $project reshapes the output by renaming _id to Name and excluding the original _id.
  • The result shows distinct name-score pairs with aggregated values.

Conclusion

Use $group with aggregation operators like $sum to create distinct pairs from duplicate documents. The $project stage helps format the final output structure as needed.

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

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements