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 query to group by _id
To group by _id in MongoDB, use the $group stage in an aggregation pipeline. This allows you to group documents by the _id field or set _id: null to group all documents together.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$fieldName",
aggregatedField: { $operator: "expression" }
}
}
]);
Sample Data
db.demo529.insertMany([
{ "Score": 10 },
{ "Score": 20 },
{ "Score": 10 },
{ "Score": 10 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8b1d5bef4dcbee04fbbbe4"),
ObjectId("5e8b1d5fef4dcbee04fbbbe5"),
ObjectId("5e8b1d61ef4dcbee04fbbbe6"),
ObjectId("5e8b1d62ef4dcbee04fbbbe7")
]
}
Display Sample Data
db.demo529.find();
{ "_id": ObjectId("5e8b1d5bef4dcbee04fbbbe4"), "Score": 10 }
{ "_id": ObjectId("5e8b1d5fef4dcbee04fbbbe5"), "Score": 20 }
{ "_id": ObjectId("5e8b1d61ef4dcbee04fbbbe6"), "Score": 10 }
{ "_id": ObjectId("5e8b1d62ef4dcbee04fbbbe7"), "Score": 10 }
Example: Group All Documents
To count all documents by grouping them together, set _id: null ?
db.demo529.aggregate([
{
$group: {
_id: null,
count: { $sum: 1 }
}
}
]);
{ "_id": null, "count": 4 }
Example: Group by Score Field
To group documents by the Score field and count occurrences ?
db.demo529.aggregate([
{
$group: {
_id: "$Score",
count: { $sum: 1 }
}
}
]);
{ "_id": 10, "count": 3 }
{ "_id": 20, "count": 1 }
Conclusion
Use $group in MongoDB aggregation to group documents by any field. Set _id: null to group all documents together, or use _id: "$fieldName" to group by specific field values.
Advertisements
