使用Mongo Driver读取Mongo集合数组属性失败问题求助
解决C# Mongo Driver读取数组属性时的反序列化错误
错误原因
执行Unwind操作后,Mongo会将原文档中的roles数组拆分为单个文档对象,但你的Employee类中roles字段定义为List<Role>类型,驱动尝试将单个Document反序列化为数组类型,因此抛出Cannot deserialize a 'List<roles>' from BsonType 'Document'错误。
前提确认
确保你的实体类定义正确,示例如下:
public class Employee { public ObjectId Id { get; set; } public int EmpId { get; set; } public List<Role> roles { get; set; } } public class Role { public int roleId { get; set; } public string roleName { get; set; } }
解决方案
方案1:强类型Unwind+匿名投影
直接通过强类型指定Unwind的字段,投影时直接访问单个Role对象的属性:
var data = _db.GetCollection<Employee>(collection) .Aggregate() .Unwind(e => e.roles) .Project(i => new { roleId = i.roles.roleId }); var output1 = data.ToList();
方案2:定义DTO接收Unwind结果
如果需要保留更多字段,可以定义专门的DTO类,其中roles字段为单个Role对象而非数组:
public class EmployeeUnwindDto { public ObjectId Id { get; set; } public int EmpId { get; set; } public Role roles { get; set; } } // 查询代码 var data = _db.GetCollection<Employee>(collection) .Aggregate() .Unwind<Employee, EmployeeUnwindDto>(e => e.roles); var output1 = data.Project(i => new { roleId = i.roles.roleId }).ToList();
方案3:字符串指定字段(兼容旧版本驱动)
如果使用的驱动版本不支持强类型Unwind,可以用字符串指定字段,投影时正确访问单个Role对象的属性:
var data = _db.GetCollection<Employee>(collection) .Aggregate() .Unwind("roles") .Project(i => new { roleId = i.roles.roleId }); var output1 = data.ToList();
内容的提问来源于stack exchange,提问作者Anil
相关产品推荐
相关产品推荐

