如何用.NET MongoDB驱动创建投影:排除字段并保留其长度?
解决建议
你可以通过同时添加长度计算投影和排除原字段来实现需求,具体修改方案有两种风格可选:
方案一:遍历构建投影操作列表
private ProjectionDefinition<BsonDocument> GetFullRedactionProjection() { var projectionOperations = new List<ProjectionDefinition<BsonDocument>>(); foreach (var item in RedactedPropertyList) { // 添加新字段存储原字段的长度(根据字段类型选择操作符) // 字符串类型用 $strLenCP,数组类型用 $size,示例以字符串为例 var lengthProjection = Builders<BsonDocument>.Projection .Expression(doc => new BsonDocument($"{item}_Length", BsonExpression.Create($"{{ $strLenCP: '{item}' }}"))); // 排除原字段 var excludeProjection = Builders<BsonDocument>.Projection.Exclude(item); projectionOperations.Add(lengthProjection); projectionOperations.Add(excludeProjection); } // 合并所有投影操作,空列表时默认保留_id return projectionOperations.Count == 0 ? Builders<BsonDocument>.Projection.Include("_id") : Builders<BsonDocument>.Projection.Combine(projectionOperations); }
方案二:保持原Aggregate累加风格
private ProjectionDefinition<BsonDocument> GetFullRedactionProjection() { return RedactedPropertyList.Aggregate(Builders<BsonDocument>.Projection.Empty, (current, item) => { // 构建长度计算投影 var lengthProjection = Builders<BsonDocument>.Projection .Expression(doc => new BsonDocument($"{item}_Length", BsonExpression.Create($"{{ $strLenCP: '{item}' }}"))); // 构建排除原字段的投影 var excludeProjection = Builders<BsonDocument>.Projection.Exclude(item); // 合并当前投影与新操作 return current.Combine(lengthProjection).Combine(excludeProjection); }); }
关键说明
- 操作符选择:如果被处理的字段是数组,将
$strLenCP替换为$size即可;若字段类型不固定,可使用$cond判断类型后选择对应计算方式。 - 字段命名:示例用
{原字段名}_Length作为新字段名,可根据业务需求自定义命名规则。 - 空列表处理:当
RedactedPropertyList为空时,返回保留_id的默认投影,避免因空投影导致查询返回所有字段。
内容的提问来源于stack exchange,提问作者Igorek
相关产品推荐
相关产品推荐

