计算MongoDB和C#驱动程序中的总和

时间:2014-01-14 13:41:58

标签: c# mongodb mongodb-.net-driver

我想通过C#驱动程序计算mongodb中字段的总和,同时满足一定的条件,我不知道如何解决这个问题。 我需要的是这样的东西:

var collection = Db.GetCollection<T>(key);
var sumValue = collection.Find(new QueryDocument("Checked", true))
                         .Aggregate(new BsonDocument ("$Sum", "Debit"));

但我不知道如何使这项工作。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

如果您不想在检索结果后在本地进行计算,则必须使用聚合框架。请检查sintax,因为我没有测试过它。

var match = new BsonDocument 
                { 
                    { 
                        "$match", 
                        new BsonDocument 
                            { 
                                {"Checked", "true"}                             
                            } 
                    } 
                };


var group = new BsonDocument 
                { 
                    { 
                        "$group", 
                        new BsonDocument 
                            { 
                                {"_id", new BsonDocument {"_id","$_id"}},
                                {"sum", new BsonDocument {"$sum","$Debit"}
                            } 
                    } 
                };

var pipeline = new[] {match, group }; 
var result = coll.Aggregate(pipeline);

Here你有更多的例子。