MongoDB .NET Driver:使用PullFilter移除字符串数组元素失败求助
如何用MongoDB .NET Driver的PullFilter移除字符串数组中的指定元素
问题场景
需要移除MongoDB文档中字符串数组Options里的指定元素,使用PullFilter时出现两种错误:
- 直接传入字符串值,报错:
"JSON reader was expecting a value but found 'Remove'." - 使用lambda表达式匹配元素,报错:
"{document} is not supported."
文档结构如下:
{ "Name" : "Test", "Type" : NumberInt(1), "Options" : [ "Testing", "Tested", "Remove this one" ] }
错误原因
- 第一种尝试错误:
PullFilter的第二个参数需要过滤条件定义(FilterDefinition),直接传入字符串值会导致驱动无法解析成合法的MongoDB查询语法。 - 第二种尝试错误:针对字符串类型的数组元素使用lambda表达式时,驱动无法正确将其转换为对应的过滤规则,
PullFilter更适用于复杂嵌套文档数组的过滤场景。
正确解法
解法1:使用Pull方法(推荐,更简洁)
对于简单类型数组(如字符串、数字),直接使用Pull方法传入要移除的元素值即可:
await _Collection.UpdateOneAsync( Builders<Descriptor>.Filter.Eq(d => d.Id, id), Builders<Descriptor>.Update .Set(d => d.UpdatedBy, actioner) .Set(d => d.UpdatedOn, DateTime.Now) .Pull(d => d.Options, "Remove this one") );
解法2:正确使用PullFilter
如果一定要用PullFilter,需要显式构建针对字符串元素的过滤条件:
await _Collection.UpdateOneAsync( Builders<Descriptor>.Filter.Eq(d => d.Id, id), Builders<Descriptor>.Update .Set(d => d.UpdatedBy, actioner) .Set(d => d.UpdatedOn, DateTime.Now) .PullFilter(d => d.Options, Builders<string>.Filter.Eq(s => s, "Remove this one")) );
两种方法都能正确移除数组中匹配的元素,其中Pull方法更适合简单类型数组的操作场景。
内容的提问来源于stack exchange,提问作者Peet vd Westhuizen
相关产品推荐
相关产品推荐

