How to fetch data from MongoDB collection in C# using Regular Expression?

穿精又带淫゛_ 提交于 2021-02-05 08:00:31

问题


I am using MongoDB.Drivers nuget package in my MVC (C#) web application to communication with MongoDB database. Now, I want to fetch data based on specific column and it's value. I used below code to fetch data.

var findValue = "John";
                var clientTest1 = new MongoClient("mongodb://localhost:XXXXX");
                var dbTest1 = clientTest1.GetDatabase("Temp_DB");
                var empCollection = dbTest1.GetCollection<Employee>("Employee");
                var builder1 = Builders<Employee>.Filter;
                var filter1 = builder1.Empty;
                var regexFilter = new BsonRegularExpression(findValue, "i");
                filter1 = filter1 & builder1.Regex(x => x.FirstName, regexFilter);
                filter1 = filter1 & builder1.Eq(x => x.IsDeleted,false);
                var collectionObj = await empCollection.FindAsync(filter1);
                var dorObj = collectionObj.FirstOrDefault();

But, the above code is performing like query. It means it is working as (select * from Employee where FirstName like '%John%') I don't want this. I want to fetch only those data whose FirstName value should match exact. (like in this case FirstName should equal John).

How can I perform this, can anyone provide me suggestions on this.

Note: I used new BsonRegularExpression(findValue, "i") to make search case-insensitive.

Any help would be highly appreciated.

Thanks


回答1:


I would recommend storing a normalized version of your data, and index/search upon that. It will likely be considerably faster than using regex. Sure, you'll eat up a little more storage space by including "john" alongside "John", but your data access will be faster since you would just be able to use a standard $eq query.

If you insist on regex, I recommend using ^ (start of line) and $ (end of line) around your search term. Remember though, that you should escape your find value so that its contents isn't treated as RegEx.

This should work:

string escapedFindValue = System.Text.RegularExpressions.Regex.Escape(findValue);
new BsonRegularExpression(string.Format("^{0}$", escapedFindValue), "i");

Or if you're using a newer framework version, you can use string interpolation:

string escapedFindValue = System.Text.RegularExpressions.Regex.Escape(findValue);
new BsonRegularExpression($"^{escapedFindValue}$", "i");


来源:https://stackoverflow.com/questions/49377435/how-to-fetch-data-from-mongodb-collection-in-c-sharp-using-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!