Search code examples
c#mongodbmongodb-.net-driver

Can't sum up all Int32 field values


I've got a mongo db collection with documents like this enter image description here

All I need is to count the total sum of the "debt" fields of all documents. But I have no idea of how to make it. The official docs seem to be too obscure and don't help at all because there's absolutely no information on how to use C# driver 3.6+

I came across this thread C# Mongodb. Sum field for all documents and tried to use the approach with Sum() like this:

var result = m_Counterparties.AsQueryable()
                .Where(x => !x[CounterpartyFields.ID].Equals(ObjectId.Empty))
                .Sum(x => x[CounterpartyFields.DEBT].AsInt32);
             WriteLine(result);  

and I always get 0 as a result but you can see it must be at least 100


Solution

  • So the problem here is that MongoDB C# driver needs to translate your lambda expression into aggregation. You can run a profiler to observe how it gets translated. So your code with:

    x => x[CounterpartyFields.DEBT].AsInt32
    

    is translated into:

    {
        "$group" : {
            "_id" : 1,
            "__result" : {
                "$sum" : "$debt.AsInt32"
            }
        }
    }
    

    And this is not what you're looking for.

    To fix that you should get rid of AsInt32 and to make it compileable you can use below code:

    .Sum(x => (int)x[CounterpartyFields.DEBT]);