Challenge 2: Add a $match Filter — Possible Solution ==================================================================== db.products.aggregate([ { $match: { in_stock: true } }, { $group: { _id: "$category", product_count: { $sum: 1 }, avg_price: { $avg: "$price" } } }, { $sort: { product_count: -1 } } ]) WHY THIS WORKS AS AN ANSWER ------------------------------ The new $match stage goes FIRST, before $group — filtering out-of-stock products before they're ever counted or averaged, the same as SQL evaluating WHERE before GROUP BY. Position matters here for two reasons, not just one: 1. Correctness: if $match ran AFTER $group, there would be no in_stock field left to filter on — $group's output documents only contain _id, product_count, and avg_price, since $group discards every field it wasn't told to keep or compute. The filter would either error or silently match nothing. 2. Performance: putting $match first lets MongoDB filter out documents (and use an index on in_stock, if one exists) before doing any grouping work at all, rather than grouping the entire collection and only then throwing rows away.