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
MongoDB aggregate to get the count of field values of corresponding duplicate names?
To count field values for corresponding duplicate names in MongoDB, use the aggregation pipeline with $unwind, $group, and $project stages to flatten arrays, group by names, and calculate counts.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $group: {
_id: "$arrayField.nameField",
count: { $sum: 1 },
otherFields: { $push: "$arrayField.otherField" }
}},
{ $project: {
count: 1,
otherFieldCount: { $size: "$otherFields" }
}}
]);
Sample Data
db.demo558.insertOne({
_id: 100,
CountryCode: 101,
details: [
{
Name: "Chris",
Subject: "MySQL"
},
{
Name: "Chris",
Subject: "MongoDB"
},
{
Name: "Chris",
Subject: "Java"
},
{
Name: "Bob",
Subject: "Python"
},
{
Name: "Bob",
Subject: "Java"
}
]
});
{ "acknowledged": true, "insertedId": 100 }
View Sample Data
db.demo558.find();
{
"_id": 100,
"CountryCode": 101,
"details": [
{ "Name": "Chris", "Subject": "MySQL" },
{ "Name": "Chris", "Subject": "MongoDB" },
{ "Name": "Chris", "Subject": "Java" },
{ "Name": "Bob", "Subject": "Python" },
{ "Name": "Bob", "Subject": "Java" }
]
}
Count Duplicate Names and Subjects
db.demo558.aggregate([
{ $unwind: "$details" },
{ $group: {
_id: "$details.Name",
NameCount: { $sum: 1 },
Subject: { $push: "$details.Subject" }
}},
{ $project: {
NameCount: 1,
SubjectCount: { $size: "$Subject" }
}}
]);
{ "_id": "Bob", "NameCount": 2, "SubjectCount": 2 }
{ "_id": "Chris", "NameCount": 3, "SubjectCount": 3 }
How It Works
- $unwind: Flattens the details array, creating separate documents for each array element
- $group: Groups by Name field, counts occurrences, and collects all subjects into an array
- $project: Displays the name count and calculates subject count using $size
Conclusion
Use aggregation pipeline with $unwind to flatten arrays, $group to count duplicates by name, and $project with $size to count associated field values. This approach efficiently handles nested array data for duplicate analysis.
Advertisements
