简体   繁体   English

如何使用 C# 将 MongoDB 集合中所有文档的键值求和

[英]How to sum the value of a key across all documents in a MongoDB collection with C#

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但在那个线程中没有 c# 答案代码,所以我想重新问同样的问题

here is my collection in mongodb这是我在 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"
}]

在此处输入图像描述

i want to sum all the key balance value and put it in a variable but i dont how to do it我想总结所有关键余额值并将其放入一个变量中,但我不知道该怎么做

please help请帮忙

So for simplicity lets put some cut-down documents into our MongoDB collection that we'll work with.因此,为简单起见,让我们将一些精简的文档放入我们将使用的 MongoDB 集合中。

> 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.就像您分享的其他 StackOverflow 帖子一样,我们需要按阶段运行一个聚合管道。

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.它们只会是聚合管道返回的一项或一项,这样我们可以使用一些 Linq 来获取文档,如果集合中没有任何内容,则默认为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM