Aggregation Pipelines
SDK method: aggregate.
This example expects string status values and numeric amount values in orders:
String command = """
db.orders.aggregate([
{$match: {status: ?}},
{$group: {_id: '$customerId', total: {$sum: '$amount'}}},
{$sort: {total: -1, _id: 1}},
{$limit: 10}
], {allowDiskUse: true, maxTimeMS: 5000})
""";
try (PreparedStatement ps = conn.prepareStatement(command)) {
ps.setString(1, "paid");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString("_JSON"));
}
}
}
The server filters paid orders, sums amount by customerId, sorts and returns the first ten groups. The output _id is a group key, not an order primary key. Grouping does not itself sort results; see MongoDB $group. The total field is not a separate JDBC column; parse it from _JSON.
To map the result to an entity or call getBigDecimal("total"), append {$project: {_id: 0, customerId: '$_id', total: 1}} to the pipeline and keep the default preRead=true.
Supported options are allowDiskUse, batchSize, maxTimeMS, maxAwaitTimeMS, bypassDocumentValidation, collation, comment, and hint. batchSize controls SDK retrieval batches, not the total result size buffered by the driver. hint is an index hint, not a pagination Hint. Use explicit $skip and $limit stages for pagination.