Menu
CoddyTech

Averages Within Groups

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

A group can compute several summaries of the same incoming documents. The grouping expression chooses which records belong together; each accumulator computes a separate output field.

{$group: {
    _id: '$team',
    players: {$sum: 1},
    averageScore: {$avg: '$score'}
}}

For two players on the same team scoring 8 and 12, players is 2 and averageScore is 10. The quoted '$score' reads the score from each incoming player. Apply the same idea to book years. The output field name is your choice; the field reference identifies the values to average.

challenge icon

Challenge

Easy

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

Group books by genre and return _id, count and averageYear. Sort the output by _id ascending. Run: classic has count 1 and averageYear 1815; scifi has count 2 and averageYear 1972.

Try it yourself

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

All lessons in Databases with MongoDB

Practice on your own: Express playground