繁体   English   中英

获取mongodb中所有字段的总和 c#

[英]Get summation of all field in mongodb c#

我有一个 mongodb 看起来像这样

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

我需要使用 mongodb c# 客户端获取特定客户端 ID 和产品 ID 的权重值总和,我该怎么做?

我试过了,但它总是返回 0

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

谢谢

我想你正在寻找这个查询,所以你可以试试这个代码:

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM