如何用MongoDB C#驱动将指定集合数据转换为MyObject列表?
C#实现MongoDB集合数据转换为指定结构的List
我来帮你搞定这个需求——把MongoDB里带数组的文档转换成你想要的List<MyObject>格式,下面是具体的实现方案,基于官方MongoDB .NET驱动完成。
首先明确目标:把MongoDB中类似这样的文档:
{ _id : 1, key : "key1", value : [ "val11", "val12"] } { _id : 2, key : "key2", value : [ "val21", "val22", "val23"] }
转换成List<MyObject>,其中MyObject的结构是:
public class MyObject { public string Category { get; set; } public string Name { get; set; } }
最终得到的结果格式为:
[{Category: "key1", Name: "val11"}, {Category: "key1", Name:"val12"}, {Category: "key2", Name: "val21"}, {Category:"key2",Name:"val22"}, {Category: "key2", Name: "val23"}]
方案一:使用MongoDB聚合管道(推荐,数据库端处理)
这种方式在数据库层面完成数组展开和字段映射,减少客户端的数据传输量,效率更高,尤其适合数据量大的场景。
步骤1:定义实体类
先定义对应MongoDB原始文档的类,以及目标转换类:
// 目标转换类 public class MyObject { public string Category { get; set; } public string Name { get; set; } } // 对应MongoDB原始文档的实体类 public class MongoSourceDocument { public int _id { get; set; } public string key { get; set; } public List<string> value { get; set; } }
步骤2:编写聚合查询代码
使用Unwind展开数组,再用Project映射字段:
using MongoDB.Driver; using System.Collections.Generic; using System.Threading.Tasks; public class MongoDataTransformer { private readonly IMongoCollection<MongoSourceDocument> _sourceCollection; public MongoDataTransformer() { // 替换成你的MongoDB连接字符串、数据库名和集合名 var mongoClient = new MongoClient("mongodb://localhost:27017"); var database = mongoClient.GetDatabase("YourDatabaseName"); _sourceCollection = database.GetCollection<MongoSourceDocument>("YourCollectionName"); } public async Task<List<MyObject>> GetTransformedListAsync() { var aggregationPipeline = _sourceCollection.Aggregate() // 展开value数组,每个数组元素生成一个独立的文档 .Unwind(doc => doc.value) // 将原始的key映射为Category,展开后的value映射为Name .Projection(doc => new MyObject { Category = doc.key, Name = doc.value }); // 执行聚合并返回结果列表 return await aggregationPipeline.ToListAsync(); } }
如果不想定义原始文档的实体类,也可以直接用BsonDocument处理:
public async Task<List<MyObject>> GetTransformedListWithoutEntityAsync() { var aggregationPipeline = _sourceCollection.Aggregate<BsonDocument>() .Unwind("$value") .Projection("{ Category: $key, Name: $value, _id: 0 }") // 排除_id字段 .As<MyObject>(); return await aggregationPipeline.ToListAsync(); }
方案二:客户端处理(简单直接,适合小数据量)
如果数据量不大,也可以先把所有文档查询到客户端,再用LINQ展开数组并转换:
public async Task<List<MyObject>> GetTransformedListClientSideAsync() { // 查询所有原始文档 var allSourceDocs = await _sourceCollection.Find(_ => true).ToListAsync(); // 用SelectMany展开数组,逐个转换为MyObject return allSourceDocs .SelectMany(doc => doc.value.Select(val => new MyObject { Category = doc.key, Name = val })) .ToList(); }
注意事项
- 确保已安装官方MongoDB .NET驱动NuGet包:
MongoDB.Driver - 替换代码中的连接字符串、数据库名和集合名为你实际的配置
- 数据量大时优先选择方案一,避免客户端加载过多数据
内容的提问来源于stack exchange,提问作者Darkersan
相关产品推荐
相关产品推荐

