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
Select documents grouped by field in MongoDB?
To select documents grouped by field in MongoDB, use the $group stage in an aggregation pipeline along with $project to reshape the output. The $group stage groups documents by specified field values and accumulates data using operators like $push.
Syntax
db.collection.aggregate([
{
"$group": {
"_id": { "field1": "$field1", "field2": "$field2" },
"groupedData": { "$push": { "field3": "$field3" } }
}
},
{
"$project": {
"_id": "$_id.field1",
"field2": "$_id.field2",
"groupedData": 1
}
}
]);
Sample Data
db.demo540.insertMany([
{ "id": 1, "Name": "Chris", "CountryName": "US" },
{ "id": 1, "Name": "Chris", "CountryName": "UK" },
{ "id": 1, "Name": "Chris", "CountryName": "AUS" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8ca368ef4dcbee04fbbc0e"),
ObjectId("5e8ca36bef4dcbee04fbbc0f"),
ObjectId("5e8ca370ef4dcbee04fbbc10")
]
}
View Sample Data
db.demo540.find();
{ "_id": ObjectId("5e8ca368ef4dcbee04fbbc0e"), "id": 1, "Name": "Chris", "CountryName": "US" }
{ "_id": ObjectId("5e8ca36bef4dcbee04fbbc0f"), "id": 1, "Name": "Chris", "CountryName": "UK" }
{ "_id": ObjectId("5e8ca370ef4dcbee04fbbc10"), "id": 1, "Name": "Chris", "CountryName": "AUS" }
Example: Group by ID and Name
Group documents by id and Name fields, collecting all CountryName values into an array ?
db.demo540.aggregate([
{
"$group": {
"_id": {
"id": "$id",
"Name": "$Name"
},
"details": {
"$push": {
"CountryName": "$CountryName"
}
}
}
},
{
"$project": {
"_id": "$_id.id",
"Name": "$_id.Name",
"details": 1
}
}
]);
{
"details": [
{ "CountryName": "US" },
{ "CountryName": "UK" },
{ "CountryName": "AUS" }
],
"_id": 1,
"Name": "Chris"
}
How It Works
-
$groupgroups documents by the_idfield containing multiple grouping criteria -
$pushaccumulates values from grouped documents into an array -
$projectreshapes the output by extracting grouped fields and renaming the_id
Conclusion
Use $group with $push to collect grouped documents into arrays, then $project to format the final output. This approach effectively groups documents by specified fields while preserving related data in structured arrays.
Advertisements
