MongoDB — Grouping & Deconstruction Stages ($group & $unwind)

🍃 MongoDB 7.0+ 🟢 Chapter 33 of 50 📂 Phase 07: Aggregation Framework Pipeline 📅 2026 Edition

Group records with $group, calculate metrics ($sum, $avg, $min, $max), and deconstruct arrays using $unwind.

1Deconstructing Arrays with $unwind
$unwind & $group Combination
db.posts.aggregate([
  // Flattens array: outputs 1 document per tag
  { $unwind: "$tags" },
  
  // Group by tag and count frequency
  { $group: { _id: "$tags", count: { $sum: 1 } } },
  
  { $sort: { count: -1 } }
]);
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on MongoDB 7.0+ Standards · Last updated August 2026