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 aggregation to combine or merge fields and then count?
To combine or merge fields and then perform count, use $group along with $sum and $sort. This aggregation approach groups documents by field values and counts occurrences in each group.
Syntax
db.collection.aggregate([
{ $group: { "_id": "$fieldName", "COUNT": { $sum: 1 } } },
{ $sort: { "COUNT": -1 } },
{ $limit: n }
]);
Sample Data
db.demo647.insertMany([
{"Subject": "MySQL"},
{"Subject": "MongoDB"},
{"Subject": "MySQL"},
{"Subject": "SQL Server"},
{"Subject": "MongoDB"},
{"Subject": "PL/SQL"},
{"Subject": "MongoDB"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e9c86316c954c74be91e6ee"),
ObjectId("5e9c86356c954c74be91e6ef"),
ObjectId("5e9c86376c954c74be91e6f0"),
ObjectId("5e9c86406c954c74be91e6f1"),
ObjectId("5e9c86436c954c74be91e6f2"),
ObjectId("5e9c864b6c954c74be91e6f3"),
ObjectId("5e9c86c16c954c74be91e6f4")
]
}
Display all documents from the collection ?
db.demo647.find();
{ "_id" : ObjectId("5e9c86316c954c74be91e6ee"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e9c86356c954c74be91e6ef"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e9c86376c954c74be91e6f0"), "Subject" : "MySQL" }
{ "_id" : ObjectId("5e9c86406c954c74be91e6f1"), "Subject" : "SQL Server" }
{ "_id" : ObjectId("5e9c86436c954c74be91e6f2"), "Subject" : "MongoDB" }
{ "_id" : ObjectId("5e9c864b6c954c74be91e6f3"), "Subject" : "PL/SQL" }
{ "_id" : ObjectId("5e9c86c16c954c74be91e6f4"), "Subject" : "MongoDB" }
Example: Group, Count and Sort
Following is the query to combine or merge fields then count ?
db.demo647.aggregate([
{ "$group": { "_id": "$Subject", "COUNT": { "$sum": 1 } } },
{ "$sort": { "COUNT": -1 } },
{ "$limit": 2 }
]);
{ "_id" : "MongoDB", "COUNT" : 3 }
{ "_id" : "MySQL", "COUNT" : 2 }
How It Works
-
$groupcombines documents by the Subject field value -
$sum: 1counts each document in the group -
$sort: { "COUNT": -1 }orders results by count in descending order -
$limit: 2returns only the top 2 results
Conclusion
Use MongoDB's aggregation pipeline with $group and $sum to combine documents by field values and count occurrences. Add $sort and $limit to organize and restrict results.
Advertisements
