修剪值存在于Mongo数据库中 [英] Trim Values existing in Mongo Database

查看:0
本文介绍了修剪值存在于Mongo数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的集合中的数据可能在前面和后面都有空格,我想要做的是修剪所有空格并进行==比较,以获得适当的记录我的代码如下:

var test = await _dataStore.FindMostRecentAsync(x => x.Barcodes.PrimaryBarcode.Trim() == barcode.Trim());

当我运行这段代码时,它给我一个错误.Trim()不受支持(它仅在我修剪我传入的条形码字符串变量时起作用。

剪裁集合中数据的最佳方式是什么,以便我可以进行精确比较。

堆栈跟踪

在 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](FilterDefinition1 过滤器,FindOptions2 options) at MongoDB.Driver.MongoCollectionImpl1.FindAsync[TProjection](IClientSessionHandle 会话、筛选器定义1 filter, FindOptions2个选项、 取消令牌取消令牌)在 MongoDB.Driver.MongoCollectionImpl1.<>c__DisplayClass37_01.b__0(IClientSessionHandle 会议)在 MongoDB.Driver.MongoCollectionImpl1.UsingImplicitSessionAsync[TResult](Func2 函数异步、取消令牌取消令牌)

推荐答案

您必须使用聚合函数才能调用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],您将能够删除投影阶段。

这篇关于修剪值存在于Mongo数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆