Aggregation¶
Goose provides an AggregationCursor[T] builder to create type-safe MongoDB aggregation pipelines.
Building Pipelines¶
You can build a pipeline using chainable methods corresponding to MongoDB aggregation stages.
cursor, err := goose.Aggregate[User](ctx).
Match(bson.M{"status": "active"}).
Group(bson.M{"_id": "$role", "count": bson.M{"$sum": 1}}).
Sort(bson.M{"count": -1}).
Exec()
if err != nil {
log.Fatal(err)
}
var results []RoleCount
if err := cursor.All(ctx, &results); err != nil {
log.Fatal(err)
}
Type Safety
The Aggregate[T] function ensures that the resulting cursor yields documents of type T or whatever type you decode them into.