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

如何在C#中实现MongoDB Aggregate分组后的条件求和?

使用C#实现MongoDB分组后的条件求和操作

没问题,我来帮你搞定这个MongoDB聚合分组后的条件求和需求!根据你提供的member集合数据,我们可以按_Ten字段分组,然后针对不同的条件(比如角色类型、活跃状态)统计数量,下面是具体的实现步骤和代码示例。

1. 定义实体类

首先我们需要定义和集合文档对应的C#实体类,方便MongoDB驱动进行序列化和反序列化:

using MongoDB.Bson;

public class User
{
    public ObjectId Id { get; set; }
    public ObjectId _Ten { get; set; }
    public bool Active { get; set; }
    public string Role { get; set; }
    public string _t { get; set; }
}

2. 使用强类型API实现聚合操作

MongoDB的C#驱动提供了强类型的Aggregate API,写法更简洁直观。这里我们以按_Ten分组,统计每个租户下管理员、贡献者以及活跃用户的数量为例:

using MongoDB.Driver;
using System.Threading.Tasks;

// 初始化Mongo客户端和集合
var mongoClient = new MongoClient("mongodb://localhost:27017");
var database = mongoClient.GetDatabase("你的数据库名称");
var userCollection = database.GetCollection<User>("member");

// 构建聚合管道
var aggregationResult = userCollection.Aggregate()
    .Group(
        // 指定分组键:按_Ten字段分组
        user => user._Ten,
        // 定义分组后的统计字段
        group => new
        {
            TenantId = group.Key,
            // 统计Administrator角色的数量:符合条件加1,否则加0,求和得到总数
            AdminCount = group.Sum(u => u.Role == "Administrator" ? 1 : 0),
            // 统计Contributor角色的数量
            ContributorCount = group.Sum(u => u.Role == "Contributor" ? 1 : 0),
            // 统计活跃用户的数量(active为true)
            ActiveUserTotal = group.Sum(u => u.Active ? 1 : 0)
        }
    );

// 执行聚合并获取结果
var resultList = await aggregationResult.ToListAsync();

// 遍历输出结果
foreach (var item in resultList)
{
    Console.WriteLine($"租户ID: {item.TenantId}");
    Console.WriteLine($"管理员数量: {item.AdminCount}");
    Console.WriteLine($"贡献者数量: {item.ContributorCount}");
    Console.WriteLine($"活跃用户总数: {item.ActiveUserTotal}");
    Console.WriteLine("------------------------");
}

3. 复杂条件的求和示例

如果需要同时满足多个条件(比如活跃的管理员用户数量),只需要调整Sum里的判断逻辑即可:

ActiveAdminCount = group.Sum(u => u.Active && u.Role == "Administrator" ? 1 : 0)

4. 使用原生BsonDocument构建聚合管道(兼容旧版本驱动)

如果你使用的是较旧版本的MongoDB驱动,或者需要更贴近原生MongoDB语法的写法,可以用BsonDocument来构建聚合管道:

using MongoDB.Bson;
using MongoDB.Driver;

var pipeline = new BsonDocument[]
{
    new BsonDocument("$group",
        new BsonDocument
        {
            { "_id", "$_Ten" },
            { "AdminCount", new BsonDocument("$sum",
                new BsonDocument("$cond",
                    new BsonArray
                    {
                        new BsonDocument("$eq", new BsonArray { "$role", "Administrator" }),
                        1,
                        0
                    }))
            },
            { "ActiveUserTotal", new BsonDocument("$sum",
                new BsonDocument("$cond",
                    new BsonArray
                    {
                        "$active",
                        1,
                        0
                    }))
            }
        })
};

var result = await userCollection.Aggregate<BsonDocument>(pipeline).ToListAsync();

// 解析BsonDocument结果
foreach (var doc in result)
{
    Console.WriteLine($"租户ID: {doc["_id"]}");
    Console.WriteLine($"管理员数量: {doc["AdminCount"]}");
    Console.WriteLine($"活跃用户总数: {doc["ActiveUserTotal"]}");
    Console.WriteLine("------------------------");
}

以上两种方式都能实现分组后的条件求和,你可以根据自己的项目环境和习惯选择合适的写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:24:43