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 Group query to get the count of repeated marks in documents?
To get the count of repeated marks in MongoDB documents, use the $group aggregation stage with $sum to count occurrences of each unique mark value.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$fieldName",
count: { $sum: 1 }
}
}
])
Sample Data
db.demo676.insertMany([
{"Marks": 87},
{"Marks": 75},
{"Marks": 87},
{"Marks": 65},
{"Marks": 65}
])
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea41eed04263e90dac943f2"),
ObjectId("5ea41ef304263e90dac943f3"),
ObjectId("5ea41ef404263e90dac943f4"),
ObjectId("5ea41ef704263e90dac943f5"),
ObjectId("5ea41ef804263e90dac943f6")
]
}
Display all documents from the collection ?
db.demo676.find()
{ "_id": ObjectId("5ea41eed04263e90dac943f2"), "Marks": 87 }
{ "_id": ObjectId("5ea41ef304263e90dac943f3"), "Marks": 75 }
{ "_id": ObjectId("5ea41ef404263e90dac943f4"), "Marks": 87 }
{ "_id": ObjectId("5ea41ef704263e90dac943f5"), "Marks": 65 }
{ "_id": ObjectId("5ea41ef804263e90dac943f6"), "Marks": 65 }
Example: Count Repeated Marks
Group documents by marks and count occurrences ?
db.demo676.aggregate([
{
$group: {
_id: { "Marks": "$Marks" },
"Count": { $sum: 1 }
}
}
])
{ "_id": { "Marks": 75 }, "Count": 1 }
{ "_id": { "Marks": 65 }, "Count": 2 }
{ "_id": { "Marks": 87 }, "Count": 2 }
How It Works
-
$groupgroups documents by the specified field (_id: {"Marks": "$Marks"}) -
$sum: 1adds 1 for each document in the group, effectively counting occurrences - The result shows each unique mark value and how many times it appears
Conclusion
Use $group with $sum: 1 in MongoDB aggregation to count repeated values. This approach efficiently groups documents by field values and returns occurrence counts for analysis.
Advertisements
