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
How can I aggregate collection and group by field count in MongoDB?
In MongoDB, use the $group stage with aggregate() to group documents by field values and count occurrences. The $sum operator with value 1 counts documents in each group.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$fieldName",
count: { $sum: 1 }
}
}
]);
Sample Data
db.demo616.insertMany([
{ "details": { "Name": "Chris", "Age": 21 } },
{ "details": { "Name": "Chris", "Age": 22 } },
{ "details": { "Name": "Bob", "Age": 23 } },
{ "details": { "Name": "Sam", "Age": 21 } },
{ "details": { "Name": "Chris", "Age": 24 } }
]);
Display Collection Data
db.demo616.find();
{ "_id" : ObjectId("5e99bfac65492f6c60d00283"), "details" : { "Name" : "Chris", "Age" : 21 } }
{ "_id" : ObjectId("5e99bfb065492f6c60d00284"), "details" : { "Name" : "Chris", "Age" : 22 } }
{ "_id" : ObjectId("5e99bfb865492f6c60d00285"), "details" : { "Name" : "Bob", "Age" : 23 } }
{ "_id" : ObjectId("5e99bfbd65492f6c60d00286"), "details" : { "Name" : "Sam", "Age" : 21 } }
{ "_id" : ObjectId("5e99bfc165492f6c60d00287"), "details" : { "Name" : "Chris", "Age" : 24 } }
Group by Name and Count Documents
Following query groups documents by details.Name and counts occurrences ?
db.demo616.aggregate([
{
$group: {
_id: "$details.Name",
Total: { $sum: 1 }
}
}
]);
{ "_id" : "Sam", "Total" : 1 }
{ "_id" : "Bob", "Total" : 1 }
{ "_id" : "Chris", "Total" : 3 }
Key Points
-
$groupstage groups documents by the_idfield value. -
$sum: 1adds 1 for each document in the group, effectively counting them. - Use dot notation like
"$details.Name"to group by nested fields.
Conclusion
MongoDB's $group stage with $sum: 1 efficiently counts documents by field values. This aggregation pattern is essential for generating frequency statistics from your data.
Advertisements
