querydrill

Learn ›Aggregation ›Grouping and accumulators

$group: the heart of aggregation

This is where aggregation stops being “find with extra steps” and people usually stall. It is worth slowing down for one idea: in $group, _id is not an id. It is the thing you are grouping by.

Think:

Take multiple documents and combine them into groups.

Suppose we have:

Order 1 → userId 101
Order 2 → userId 101
Order 3 → userId 102

Now:

{
  $group: {
    _id: "$userId"
  }
}

Result:

[
  { _id: 101 },
  { _id: 102 }
]

MongoDB says:

All documents where userId = 101
        ↓
Put them in group 101

All documents where userId = 102
        ↓
Put them in group 102

Try it

db.orders.aggregate([
  {
    $group: {
      _id: "$userId"
    }
  },
  { $sort: { _id: 1 } },
  { $limit: 5 }
])

200 orders in, one document per distinct userId out. No count, no total - _id on its own answers “which users have ordered at all”.