You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中获取MongoDB聚合统计值遇错误,求解决方案

解决C#中MongoDB统计匹配EmployeeId的Ticket数量问题

错误原因与聚合写法修正

你遇到的错误是因为调用.Count()后返回的AggregateCountResult类型没有Count属性,正确的取值属性是Value。修正后的代码如下:

public int GetUserTicketCount(User user)
{
    var countResult = collectionOfTickets.Aggregate()
        .Match(x => x.employeeId == user.GetEmployeeId())
        .Count()
        .FirstOrDefault();
    
    // 处理查询结果为空的情况,默认返回0
    return countResult?.Value ?? 0;
}

更简洁高效的替代方案

对于这种简单的“匹配条件+统计数量”的场景,不需要使用聚合操作,MongoDB驱动提供了专门的CountDocuments方法,代码更简洁且性能更优:

public int GetUserTicketCount(User user)
{
    // CountDocuments返回long类型,根据实际数据量决定是否转换为int
    long totalCount = collectionOfTickets.CountDocuments(x => x.employeeId == user.GetEmployeeId());
    return (int)totalCount;
}

如果你的Ticket数量可能超过int的最大值(2^31-1),建议将返回类型改为long避免溢出。

内容的提问来源于stack exchange,提问作者Ignacio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:01:17