【问题标题】:Get summation of all field in mongodb c#获取mongodb c#中所有字段的总和
【发布时间】:2023-01-13 18:55:40
【问题描述】:

我有一个看起来像这样的 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);

谢谢

【问题讨论】:

    标签: c# mongodb mongodb-csharp-2.0


    【解决方案1】:

    我想你正在寻找 this query 所以你可以试试这个代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多