List<abcd> data = new List<abcd>(); data.Add(new abcd { name = "tbl1", fieldname = "total_amount" }); data.Add(new abcd { name = "tbl2", fieldname = "total_amount_return" }); var Pipeline = new List<BsonDocument>(); var groupFields = new BsonDocument{ { "_id", "$_id" }, { "customer", new BsonDocument("$first", "$customer") }, { "sr_no", new BsonDocument("$first", "$sr_no") }, { "untitled", new BsonDocument("$first", "$untitled") }}; // Perform all lookups first for (int i = 0; i < data.Count; i++) { Pipeline.Add(new BsonDocument("$lookup", new BsonDocument { { "from", data[i].name }, { "localField", "_process_id" }, { "foreignField", "_process_id" }, { "as", $"Products{i}" } })); // Unwind each lookup result Pipeline.Add(new BsonDocument("$unwind", new BsonDocument { { "path", $"$Products{i}" }, { "preserveNullAndEmptyArrays", true } })); // Sum each field groupFields.Add($"{data[i].fieldname}", new BsonDocument("$sum", new BsonDocument("$ifNull", new BsonArray { $"$Products{i}.{data[i].fieldname}", 0 }))); } // Group by required fields and sum the fields from each lookup Pipeline.Add(new BsonDocument("$group", groupFields));This is my Code to Get Sum from 2 or more than 2 Collection. This code is written by chatpgt but there's a problem in it that it it will multiply the total amount and return total with number of row like if total amount is 1,000 and product count in tbl1 is 4 than it will return 4,000 same is it with total amount return.
Any guidance or suggestions would be greatly appreciated.