I’m working on a Blazor WASM application with a MongoDB database, where I’m implementing a pivot table. The API below generates grouped data based on the requested rows, columns, and values. Here's the code for my current pipeline:
public class PivotRequest{ public List<string> Rows { get; set; } // E.g., ["Category", "Sub-Category"] public List<string> Columns { get; set; } // E.g., ["Region", "Salesperson"] public List<string> Values { get; set; } // E.g., ["Amount", "Quantity"]}[Authorize][HttpPost("GetPivotTableAsync")]public async Task<string> GetPivotTableAsync(PivotRequest request){ var pipeline = new List<BsonDocument>(); // AddFields to ensure values are numeric foreach (var value in request.Values) { pipeline.Add(new BsonDocument("$addFields", new BsonDocument(value, new BsonDocument("$toDouble", $"${value}")))); } // Grouping Key var groupKey = new BsonDocument(); foreach (var row in request.Rows) groupKey.Add(row, $"${row}"); foreach (var column in request.Columns) groupKey.Add(column, $"${column}"); // $group stage with accumulations var groupStage = new BsonDocument("$group", new BsonDocument { { "_id", groupKey } }); foreach (var value in request.Values) { groupStage["$group"].AsBsonDocument.Add(value, new BsonDocument("$sum", new BsonDocument("$ifNull", new BsonArray { $"${value}", 0 }))); } pipeline.Add(groupStage); // Projection to flatten the output var projection = new BsonDocument { { "_id", 0 } }; foreach (var row in request.Rows) projection.Add(row, $"$_id.{row}"); foreach (var column in request.Columns) projection.Add(column, $"$_id.{column}"); foreach (var value in request.Values) projection.Add(value, $"${value}"); pipeline.Add(new BsonDocument("$project", projection)); // Execute pipeline var collection = GetMyDb().MDB.GetCollection<BsonDocument>("d_sales_date"); var result = await collection.Aggregate<BsonDocument>(pipeline).ToListAsync(); return result.ToJson();}This Pipeline generate the data with all rows and columns, i want to generate this too but with individual row with individual column group too, and grand total for rows and columns like in this picture of google sheets:
This picture have single row group with single columns like Accessories Total, Electronics Total, East Total, North Total.It also have Grand total for all rows and columns and Grand total for full table too. The current Pipeline is generating for just Peripherals with Alice, Peripherals with Bob, power with Bob etc.
How can I modify my MongoDB aggregation pipeline to include these row and column totals dynamically?
Any guidance or suggestions would be greatly appreciated.
