C# MongoDB.所有文档的总和字段 [英] C# Mongodb. Sum field for all documents

查看:30
本文介绍了C# MongoDB.所有文档的总和字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算集合中所有文档的总数.比如我有以下三个文件:

_id: 1,客户 ID:1,现金:500_id: 2,客户 ID:1,现金:100_id: 3,客户 ID:2,现金:200

所以,我想为特定的 clientId 求和 cash 字段.对于客户端 1,我想要获得 600,对于客户端 2,我想要获得 200.这是我第一次使用 MongoDB 中的聚合框架.我检查了 SO 的文档和其他问题,但无法弄清楚为什么我必须使用 group 子句.为什么我需要它,如果只是想总结一下.我事件尝试使用 Group 但无法编译:

_collection.Aggregate().Match(t=>t.ClientId == 1).Group(null, g => new{总计 = g.Sum(o => o.Cash)});

<块引用>

方法 'Group' 没有重载需要 2 个参数

附注.我不想使用 BsonDocument 和诸如 $sum 之类的关键字.我想以更多的 C# 方式制作它.

解决方案

这样好吗?

var Total = _collection.AsQueryable().Where(x => x.ClientId == 2).Sum(x => x.Cash);

这里的聚合有点矫枉过正,但它可能是这样的:

var x = MongoCollection.Aggregate().团体(文档 =>doc.clientId,组 =>新的{clientId = group.Key,Total = group.Sum(y => y.sum)}).ToList().FirstOrDefault(c => c.clientId == 2).Total;

聚合在 Db 中执行,直到它进入 toList()

I need to calculate total for all document in the collection. For example, I have the following three documents:

_id: 1,
clientId: 1,
cash: 500

_id: 2,
clientId: 1,
cash: 100

_id: 3,
clientId: 2,
cash: 200

So, I want to sum cash field for the specific clientId. For the client 1 I want to get 600, for the client 2 I wanto get 200. It's my first usage of aggregation frameworkd in MongoDB. I checked documentation and the other questions from SO, but can't figure out, why I have to use group clause. Why do I need it, if just want to sum. I event tried to use Group but can't get it compile:

_collection.Aggregate().Match(t=>t.ClientId == 1).Group(null, g => new
            {
                Total = g.Sum(o => o.Cash)
            });

No overload for method 'Group' takes 2 arguments

PS. I don't want to use BsonDocument and such thing like $sum keywords. I want to make it in more C# way.

解决方案

is this ok?

var Total = _collection.AsQueryable().Where(x => x.ClientId == 2).Sum(x => x.Cash);

EDIT: aggregate is overkill here but it would go maybe like this:

var x = MongoCollection.Aggregate()
                    .Group(
                            doc => doc.clientId,
                            group => new
                            {
                                clientId = group.Key,
                                Total = group.Sum(y => y.sum)
                            }
                    ).ToList().FirstOrDefault(c => c.clientId == 2).Total;

aggregation is executed in Db until it goes toList()

这篇关于C# MongoDB.所有文档的总和字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆