我的集合中的数据可能在前面和后面都有空格,我想要做的是修剪所有空格并进行==比较,以获得适当的记录我的代码如下:
var test = await _dataStore.FindMostRecentAsync(x => x.Barcodes.PrimaryBarcode.Trim() == barcode.Trim());
当我运行这段代码时,它给我一个错误.Trim()
不受支持(它仅在我修剪我传入的条形码字符串变量时起作用。
![mongodb数据库设置允许远程访问 CSDN](https://p.xsw88.cn/allimgs/daicuo/20230903/4470.png)
剪裁集合中数据的最佳方式是什么,以便我可以进行精确比较。
堆栈跟踪
在
MongoDB.Driver.Linq.Translators.PredicateTranslator.GetFieldExpression(Expression
表达式)位于
MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(Expression
变量表达式、表达式类型运算符类型、常量表达式
常量表达式)位于
MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression
节点)位于
MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression
节点,IBsonSerializerRegistry序列化程序注册表)位于
MongoDB.Driver.MongoCollectionImpl1.CreateFindOperation[TProjection](FilterDefinition
1
过滤器,FindOptions2 options) at
MongoDB.Driver.MongoCollectionImpl
1.FindAsync[TProjection](IClientSessionHandle
会话、筛选器定义1 filter, FindOptions
2个选项、
取消令牌取消令牌)在
MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass37_0
1.b__0(IClientSessionHandle
会议)在
MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSessionAsync[TResult](Func
2
函数异步、取消令牌取消令牌)
推荐答案
您必须使用聚合函数才能调用trim operator。
遗憾的是,没有通过C#驱动程序进行调用的直接方法,但是您可以使用一些BsonDocuments构建一种方法,如下所示:
var barcode = " 1512356 ";
//This exclude the trimmedField from the result.
var projectionDefinition = Builders<BsonDocument>.Projection.Exclude("trimmedField");
//Call the trim operator and put it in the temporary trimmedField property (this trims the barcode on the database)
var expression = new BsonDocument(new List<BsonElement>
{
new BsonElement("trimmedField", new BsonDocument(new BsonDocument("$trim", new BsonDocument("input", "$Barcodes.PrimaryBarcode"))))
});
//Add the trimmedField to the document
var addFieldsStage = new BsonDocument(new BsonElement("$addFields", expression));
//Build a filter on the trimmedField and trim the local variable
var trimFilter = Builders<BsonDocument>.Filter.Eq(x => x["trimmedField"], barcode.Trim());
//Put it all together
var result = collection.Aggregate().AppendStage<BsonDocument>(addFieldsStage).Match(trimFilter).Project(projectionDefinition).As<YourType>().ToList();
请确保在.As<T>
中输入正确的类型,以便能够强制转换实体。
如果在您的类上方添加[BsonIgnoreExtraElements]
,您将能够删除投影阶段。
相关推荐
最新文章