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 to maintain the top count of array elements in MongoDB?
To maintain the top count of array elements in MongoDB, use the aggregation framework with $unwind to flatten arrays, $group to count frequencies, $sort to order by count, and $limit to get the top N elements.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $group: { _id: "$arrayField", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: N }
]);
Sample Data
db.topCountArrayDemo.insertMany([
{ "StudentId": 101, "StudentSubject": ["C", "MongoDB"] },
{ "StudentId": 102, "StudentSubject": ["C", "Java"] },
{ "StudentId": 103, "StudentSubject": ["C", "MongoDB"] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("..."),
ObjectId("...")
]
}
Display all documents to verify the data ?
db.topCountArrayDemo.find().pretty();
{
"_id": ObjectId("5cc6b3209cb58ca2b005e669"),
"StudentId": 101,
"StudentSubject": [
"C",
"MongoDB"
]
}
{
"_id": ObjectId("5cc6b3219cb58ca2b005e66a"),
"StudentId": 102,
"StudentSubject": [
"C",
"Java"
]
}
{
"_id": ObjectId("5cc6b3229cb58ca2b005e66b"),
"StudentId": 103,
"StudentSubject": [
"C",
"MongoDB"
]
}
Get Top 2 Array Element Counts
db.topCountArrayDemo.aggregate([
{
$unwind: "$StudentSubject"
},
{
$group: {
_id: "$StudentSubject",
Frequency: { $sum: 1 }
}
},
{
$sort: { Frequency: -1 }
},
{
$limit: 2
}
]);
{ "_id": "C", "Frequency": 3 }
{ "_id": "MongoDB", "Frequency": 2 }
How It Works
-
$unwindcreates separate documents for each array element -
$groupgroups by element value and counts occurrences using$sum: 1 -
$sortorders results by frequency in descending order (-1) -
$limitrestricts output to the top N most frequent elements
Conclusion
Use MongoDB's aggregation pipeline to efficiently count and rank array elements. The combination of $unwind, $group, $sort, and $limit provides a powerful way to analyze array data frequencies.
Advertisements
