Reputation: 1110
I want to calculate sum of a field in mongodb via C# driver, While meeting a certain condition and i don't have a clue how to work this out. What i need would be something like this:
var collection = Db.GetCollection<T>(key);
var sumValue = collection.Find(new QueryDocument("Checked", true))
.Aggregate(new BsonDocument ("$Sum", "Debit"));
But I don't know how to make this work. Any help is appreciated.
Upvotes: 1
Views: 6390
Reputation: 851
If you don't want to calculate locally after retrieve the results, you have to use Aggregation Framework. Please, check the sintax, because I haven't tested it.
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 you have more examples.
Upvotes: 1