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

如何将MongoDB的BsonDocument转换为C#的PrinterModel类?

如何将MongoDB聚合查询的BsonDocument转换为自定义PrinterModel类

针对你的场景,有三种简单易懂的转换方式,适合新手逐步理解:


方法1:手动映射(最直观,适合快速上手)

因为聚合返回的BsonDocument结构是{ "_id": { "type": "Printer" }, "total": 1 },可以直接从文档中提取对应字段赋值给PrinterModel:

// 从resultdata中取第一个聚合结果(你的场景应该只有一条数据)
var bsonDoc = resultdata.FirstOrDefault();

if (bsonDoc != null)
{
    var printerModel = new PrinterModel
    {
        // 从_id子文档中获取type字段
        Type = bsonDoc["_id"]["type"].AsString,
        // 直接获取total字段
        Total = bsonDoc["total"].AsInt32
    };
    // 现在printerModel就是你需要的对象了
}

方法2:使用MongoDB序列化器(适合重复转换场景)

通过给PrinterModel添加MongoDB序列化属性,让框架自动完成映射:

首先给模型类加上属性标注:

using MongoDB.Bson.Serialization.Attributes;

class PrinterModel
{
    // 映射MongoDB中的_id字段
    [BsonElement("_id")]
    private BsonDocument Id { get; set; }

    // 忽略该字段的直接序列化,通过Id属性间接获取Type值
    [BsonIgnore]
    public string Type 
    { 
        get => Id?["type"].AsString; 
        set => Id = new BsonDocument("type", value); 
    }

    // 直接映射MongoDB中的total字段
    [BsonElement("total")]
    public int Total { get; set; }
}

然后直接调用MongoDB的反序列化方法:

var printerModel = resultdata.FirstOrDefault()?.ToObject<PrinterModel>();

方法3:修改聚合管道(从源头简化结构)

在聚合查询时就调整输出结构,让返回的文档直接匹配PrinterModel的字段,后续转换更省心:

修改你的聚合管道,新增一个$project阶段重命名字段:

var pipeline = new BsonDocument[]
{
    // 保留你原来的$group阶段
    new BsonDocument("$group", 
        new BsonDocument("_id", new BsonDocument("type", "$type"))
        .Add("total", new BsonDocument("$sum", 1))),
    // 新增$project,将_id.type转为Type,total转为Total,同时移除_id字段
    new BsonDocument("$project", 
        new BsonDocument("Type", "$_id.type")
        .Add("Total", "$total")
        .Add("_id", 0))
};

此时查询返回的文档结构会变成{ "Type": "Printer", "Total": 1 },可以直接反序列化:

var printerModel = resultdata.FirstOrDefault()?.ToObject<PrinterModel>();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 15:02:41