Menu
CoddyTech

Filtering Group Results

Part of the Databases with MongoDB section of Coddy's Node.js journey. Lesson 23 of 29.

A computed group total does not exist on the original documents. Filter on it only after grouping has produced the summary records.

{$group: {_id: '$customer', orders: {$sum: 1}}},
{$match: {orders: {$gte: 3}}}

The first stage creates one record per customer with an order count. The second keeps customers with at least three orders. Reversing these stages would ask each individual order for an orders count it does not have. Trace the output fields after each stage before deciding where a filter belongs. The bookshelf task uses the same reasoning with genres and book counts.

challenge icon

Challenge

Easy

This is a small practice project. Its setup is provided; edit only exercise.js.

Add a match stage after the supplied group. Keep groups whose count is at least 2. Run and GET /result returns only [{"_id":"scifi","count":2}].

Try it yourself

export async function exercise(books) {
    return await books.aggregate([{ $group: { _id: '$genre', count: { $sum: 1 } } }]).toArray();
}

All lessons in Databases with MongoDB

Practice on your own: Express playground