Mongo数据库中现有的Trim值

时间:2019-05-30 20:40:10

标签: c# mongodb-query mongodb-.net-driver

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

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   variableExpression,ExpressionType operatorType,ConstantExpression   constantExpression)   MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression   节点)   MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(Expression   节点IBsonSerializerRegistry serializerRegistry)   MongoDB.Driver.MongoCollectionImpl 1.CreateFindOperation[TProjection](FilterDefinition 1   过滤器,FindOptions 2 options) at MongoDB.Driver.MongoCollectionImpl 1.FindAsync [TProjection](IClientSessionHandle   会话,FilterDefinition 1 filter, FindOptions 2个选项,   的CancellationToken cancelToken()   MongoDB.Driver.MongoCollectionImpl 1.<>c__DisplayClass37_0 1.b__0(IClientSessionHandle   会议)   MongoDB.Driver.MongoCollectionImpl 1.UsingImplicitSessionAsync[TResult](Func 2   funcAsync,CancellationToken cancellingToken)

2 个答案:

答案 0 :(得分:1)

您必须使用聚合函数才能调用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>中放入正确的Type,以便能够投射实体。

如果您在班级上方添加[BsonIgnoreExtraElements],则可以取消投影阶段。

答案 1 :(得分:0)

为此我想到的解决方案是执行以下操作:

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

我将不会修剪数据库中存在的值,而是会修剪变量,然后执行“包含”,这样我将获得与条形码相匹配的所有值,之后再使用该对象数组继续按日期或不按日期进行过滤。

我还没有找到任何方法可以使用C#MongoDriver将Trim()方法传递给集合对象

相关问题