0

i know this question is already exist in

https://stackoverflow.com/questions/4621300/how-to-sum-the-value-of-a-key-across-all-documents-in-a-mongodb-collection

but in that thread doesnt have a c# answer code, so i would like to re - ask the same question

here is my collection in mongodb

[{
  "_id": {
    "$oid": "5f310a3e644ddd24c86c961f"
  },
  "user_no": "USR-123123",
  "user_name": "Andrew Franklyn",
  "balance": 500000,
  "domicile": "Bali"
},{
  "_id": {
    "$oid": "5f310a9c9a71032c605176ba"
  },
  "user_no": "USR-9931021",
  "user_name": "Franklyn CJ",
  "balance": 304040,
  "domicile": "Bali"
},{
  "_id": {
    "$oid": "5f310abe9a71032c605176bb"
  },
  "user_no": "USR-42294",
  "user_name": "Jonathan Joestar",
  "balance": 123000,
  "domicile": "New York"
}]

enter image description here

i want to sum all the key balance value and put it in a variable but i dont how to do it

please help

M Andre Juliansyah
  • 117
  • 1
  • 2
  • 14

1 Answers1

1

So for simplicity lets put some cut-down documents into our MongoDB collection that we'll work with.

> db.test.insertMany([{
   "balance": 500000,
 },{
   "balance": 304040,
 },{
   "balance": 123000,
 }]
 )

Like the other StackOverflow post you shared, we'll need to run an aggregation pipeline with a group by stage.

var client = new MongoClient();

var db = client.GetDatabase("test");
var collection = db.GetCollection<Data>("test");

var result = await collection.Aggregate()
    .Group(data => "",
        grouping => new
        {
            Sum = grouping.Sum(y => y.Balance)
        })
    .ToListAsync();

var sum = result.FirstOrDefault()?.Sum ?? 0;

// Sum: 927040
Console.WriteLine($"Sum: {sum}");

They'll only be one or none items returned by the aggregation pipeline, this way we can use some Linq to fetch the document and just default to 0 if nothing is in the collection.

Kevin Smith
  • 13,746
  • 4
  • 52
  • 77