Get summation of all field in mongodb c#

86 views Asked by At

I have a mongodb which looks like this

[
{
    "client_id": "abc",
    "product_id": "123",
    "weight": {
        "value": 100
        "unit": "kg"
    }
},
{
    "client_id": "def",
    "product_id": "456",
    "weight": {
        "value": 200
        "unit": "kg"
    }
}
]

I need to get summation of weight value for a certain client id and product id using mongodb c# client, how can I do that?

I tried this but it is always returning 0

var total_weight = await Collection.AsQueryable()
                        .Where(
                        x => x.client_id == "abc" &&
                        x => x.product_id== "123")
                        .SumAsync(x => x.weight.value);

Thanks

1

There are 1 answers

0
J.F. On BEST ANSWER

I think you are looking for this query so you can try this code:

var total_weight = await Collection.AsQueryable<YourModel>()
                .Where(x => x.client_id == "abc" && x.product_id == "123")
                .GroupBy(x => new { x.client_id, x.product_id })
                .Select(x => x.Sum(y => y.weight.value))
                .FirstOrDefaultAsync();