Home > OS >  Remove regex from query MongoDB - C#
Remove regex from query MongoDB - C#

Time:07-19

I am using the following code in C# to acquire data from MongoDB database:

var result = GetItemsByQuery(Query<Table1>
  .Where(p => p.Field1.ToLower() == string1.ToLower()));

But this produces that MongoDB uses regex and I want to avoid that. I know that I should use collation, but I am not sure how to fix this line with that. Or is there another way that won't use regex?

CodePudding user response:

Instead of using the library method GetItemsByQuery, you should get an IMongoCollection<T> instance for the collection. As soon as you have the collection, you can use the Find method (or its async counterparts FindAsync) and specify the collation, e.g.:

IMongoCollection<Table1> coll = ...
var collation = new Collation("en_US");
var options = new FindOptions<Table1>() 
{
  Collation: collation,
};
var result = coll.Find(x => x.Field1 == string1, options);

The Collation property was added in driver version 2.4.

  • Related