MongoDB — Group
Basic Group
db.users.aggregate([
{ $group: { _id: "$country", count: { $sum: 1 } } }
])
Multiple Fields
db.users.aggregate([
{ $group: {
_id: { country: "$country", status: "$status" },
count: { $sum: 1 }
}}
])
Accumulators
db.users.aggregate([
{ $group: {
_id: "$country",
totalAge: { $sum: "$age" },
avgAge: { $avg: "$age" },
minAge: { $min: "$age" },
maxAge: { $max: "$age" },
count: { $sum: 1 }
}}
])
Group by Null (All)
db.users.aggregate([
{ $group: { _id: null, avgAge: { $avg: "$age" } } }
])
Push to Array
db.users.aggregate([
{ $group: {
_id: "$country",
names: { $push: "$name" }
}}
])
Mini Practice
- Group by field
- Use multiple accumulators
- Group by multiple fields
- Push values to array
Up Next
Continue with Lookup — joining collections.
Related Topics
Frequently Asked Questions about Group
What is Group in MongoDB?
Group is a fundamental concept in MongoDB. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Group?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Group.
Why is Group important in MongoDB?
Group is essential for MongoDB development. Understanding this concept will help you write better code and solve real-world problems more effectively.