Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
$groupgroups documents by theNamefield and sums allScorevalues for each name. -
$projectreshapes the output by renaming_idtoNameand 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.
Advertisements
