I'm building a Blazor WASM application that generates charts using MongoDB. My current implementation aggregates data from a MongoDB collection and supports multiple yFieldvalues for grouping and aggregation.
The current code works for a single match filter that applies to all fields, but I need to add individual filters for each yField. Here's the relevant part of my code:
[Authorize] [HttpPost("GetChartDataAsync")] public async Task<string> GetChartData(chartclass chart) { var collection = GetMyDb().MDB.GetCollection<BsonDocument>("d_sales_date"); var groupStage = new BsonDocument{ { "_id", $"${chart.xfield}" }}; foreach (var y in chart.yfield) { Aggregations aggregate = Aggregations.Sum; var aggregationOperator = aggregate switch { Aggregations.Sum => "$sum", Aggregations.Min => "$min", Aggregations.Max => "$max", Aggregations.Average => "$avg", _ => "$sum" }; //y field filters groupStage.Add(y.name, new BsonDocument(aggregationOperator, $"${y.name}")); } var pipeline = new List<BsonDocument>{ new BsonDocument("$group", groupStage)}; var results = await collection.Aggregate<BsonDocument>(pipeline).ToListAsync(); return results.ToJson(); } public class chartclass { public string xfield { get; set; } = ""; public List<YField> yfield { get; set; } = new(); } public class YField { public string name { get; set; } = ""; public BsonDocument filter { get; set; } = new(); public Aggregations aggregate { get; set; } = Aggregations.Sum; }I need to allow each yField to have its own filter (defined in yField.filter) so that I can match specific subsets of data for each aggregation.
For example:
For yField1, apply a match filter where fieldA > 100.For yField2, apply a match filter where fieldB == "value".
Desired Behavior:
I want to modify the pipeline to include conditional $match stages for each yField before adding its aggregation logic to the $group stage.
Any guidance or suggestions would be greatly appreciated.