Create five current orders and two archived orders
Run this setup once in mongosh on a disposable development server. Use an empty database named keplergrid_aggregation_stages. The linked exercises reuse these order numbers, prices, and dates.
const practice = db.getSiblingDB("keplergrid_aggregation_stages");
practice.orders.insertMany([
{ _id: "A-100", orderNo: "ORD-100", unitPrice: Decimal128("15.00"),
placedAt: ISODate("2026-01-01T23:45:00Z"), deliveredAt: ISODate("2026-01-02T00:15:00Z") },
{ _id: "A-101", orderNo: "ORD-101", unitPrice: Decimal128("20.00"),
placedAt: ISODate("2026-01-02T04:50:00Z"), deliveredAt: ISODate("2026-01-02T05:20:00Z") },
{ _id: "A-102", orderNo: "ORD-102", unitPrice: Decimal128("50.00"),
placedAt: ISODate("2026-01-02T10:00:00Z"), deliveredAt: ISODate("2026-01-03T11:00:00Z") },
{ _id: "A-103", orderNo: "ORD-103", unitPrice: Decimal128("99.00"),
placedAt: ISODate("2026-01-03T10:00:00Z"), deliveredAt: ISODate("2026-01-03T14:30:00Z") },
{ _id: "A-104", orderNo: "ORD-104", unitPrice: Decimal128("100.00"),
placedAt: ISODate("2026-01-04T09:00:00Z") }
]);
practice.archived_orders.insertMany([
{ _id: "H-099", orderNo: "ORD-099", unitPrice: Decimal128("30.00"),
placedAt: ISODate("2025-12-31T09:00:00Z") },
{ _id: "H-102", orderNo: "ORD-102", unitPrice: Decimal128("50.00"),
placedAt: ISODate("2026-01-02T10:00:00Z") }
]);
Count orders in two price bands
In KeplerGrid, open keplergrid_aggregation_stages.orders on a Read only connection. Select Aggregation → JSON, paste this pipeline, and choose Run pipeline.
[
{ "$bucket": {
"groupBy": "$unitPrice",
"boundaries": [20, 50, 100],
"default": "Other",
"output": { "orders": { "$sum": 1 } }
} }
]
Each adjacent pair of boundaries defines one range. Its lower value is included and its upper value is excluded. The default value names the bucket for input outside the ranges. In the numeric bucket rows, _id is the lower boundary.
Check prices that land on a boundary
Switch to Stages and select $bucket. The practice data gives five documents in Input and three band summaries in Output.
| Bucket ID | Included prices | Orders |
|---|---|---|
20 | 20.00 | 1 |
50 | 50.00, 99.00 | 2 |
"Other" | 15.00, 100.00 | 2 |
Notice that 50.00 starts the second band and 100.00 falls outside both. An empty band has no result row. If you remove default, every value must fall inside a band or the aggregation fails.
Use $switch to label each order or run several summaries with $facet.