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
Group query upon nested object in MongoDB?
To group documents by fields within nested objects in MongoDB, use dot notation with the $group aggregation stage. The dot notation allows you to access nested fields using the format "parentField.nestedField".
Syntax
db.collection.aggregate([
{
$group: {
_id: "$parentField.nestedField",
count: { $sum: 1 }
}
}
]);
Create Sample Data
db.demo617.insertMany([
{
"clientDetails": {
"Name": "Chris",
"Age": 32,
"Project": "Online Library Management System"
}
},
{
"clientDetails": {
"Name": "David",
"Age": 34,
"Project": "Online Hospital Management System"
}
},
{
"clientDetails": {
"Name": "David",
"Age": 34,
"Project": "Online Library Management System"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e99d2b86c954c74be91e69b"),
ObjectId("5e99d2b86c954c74be91e69c"),
ObjectId("5e99d2b96c954c74be91e69d")
]
}
View Sample Data
db.demo617.find();
{
"_id": ObjectId("5e99d2b86c954c74be91e69b"),
"clientDetails": {
"Name": "Chris",
"Age": 32,
"Project": "Online Library Management System"
}
}
{
"_id": ObjectId("5e99d2b86c954c74be91e69c"),
"clientDetails": {
"Name": "David",
"Age": 34,
"Project": "Online Hospital Management System"
}
}
{
"_id": ObjectId("5e99d2b96c954c74be91e69d"),
"clientDetails": {
"Name": "David",
"Age": 34,
"Project": "Online Library Management System"
}
}
Group by Nested Field
Group documents by the Project field within the clientDetails nested object ?
db.demo617.aggregate([
{
$group: {
_id: "$clientDetails.Project",
count: { $sum: 1 }
}
}
]);
{ "_id": "Online Hospital Management System", "count": 1 }
{ "_id": "Online Library Management System", "count": 2 }
Conclusion
Use dot notation with $group to group documents by nested object fields. The format "$parentField.nestedField" allows MongoDB to access and group by any field within nested objects efficiently.
Advertisements
