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
Using MongoDB Aggregate and GroupBy to get the frequency of name record
To get the frequency of name records in MongoDB, use the aggregation framework with $group stage to group documents by name and count occurrences using $sum.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$fieldName",
Frequency: { $sum: 1 }
}
}
]);
Create Sample Data
db.demo232.insertMany([
{_id: 101, Name: "Chris"},
{_id: 102, Name: "Bob"},
{_id: 103, Name: "Bob"},
{_id: 104, Name: "David"},
{_id: 105, Name: "Chris"}
]);
{
"acknowledged": true,
"insertedIds": {
"0": 101,
"1": 102,
"2": 103,
"3": 104,
"4": 105
}
}
Display Sample Data
db.demo232.find();
{ "_id": 101, "Name": "Chris" }
{ "_id": 102, "Name": "Bob" }
{ "_id": 103, "Name": "Bob" }
{ "_id": 104, "Name": "David" }
{ "_id": 105, "Name": "Chris" }
Get Name Frequency Using Aggregation
db.demo232.aggregate([
{
$group: {
_id: "$Name",
Frequency: { $sum: 1 }
}
}
]);
{ "_id": "David", "Frequency": 1 }
{ "_id": "Bob", "Frequency": 2 }
{ "_id": "Chris", "Frequency": 2 }
How It Works
-
$groupgroups documents by theNamefield value -
_id: "$Name"sets the grouping key to the Name field -
$sum: 1counts each document in the group by adding 1
Conclusion
Use MongoDB's $group aggregation stage with $sum: 1 to count document frequencies by any field. This efficiently calculates how many times each unique value appears in your collection.
Advertisements
