MongoDB SQL ‘Like’ Query Examples using C#
Today in this article, we shall see how to write MongoDB Like Query using C# MongoDB driver with regex pattern with case sensitive and insensitive search for example.
Today in this article, we will cover below aspects,
If you are interested in learning a query without a regex pattern, then please visit the below article,
I have a sample MongoDB document as below in one of the collections.
Here we shall be trying to search all the documents using a C# bson query similar to “Like“.
Scenario 1 – MongoDB Regex like Query
Let’s build C# regex query for getting Author names where the name contains a word like “J” or “j” for the Author field.
Assumptions:
“J” or “j” could be contained at the start or last or in the middle or anywhere else of Author’s name.
Query pattern
var queryExpr = new BsonRegularExpression(new Regex(search, RegexOptions.None));
C# MongoDb regex query with case-sensitive search
The above query will return to me all the Author that contains the search criteria “J” or “j” in the field value.
Query Result
C# MongoDb regex query with case-insensitive search
Query Pattern
var queryExpr = new BsonRegularExpression(new Regex(search, RegexOptions.IgnoreCase));
Query Result
The above query returns all the “Authors” whose names contain either “J” or “j”
Scenario 2 – MongoDB C# Regex query start with ‘like’
Let’s build a query to get the list of items that start with some search criteria.
Example “Ro” for Author field.
Query pattern
{ Field Name : /^J/ } Where "J" is your search cretieria.
Example Query
filter = builder.Regex("Author", "^" + search + ".*");
Search Result:
The above query returns all the Authors which starts with “J” values.
For Case insensitive query please prepare a query as explained in the above first example.
Scenarios 3 – MongoDB C# Regex query end with ‘like’
Let’s build a query to Get the list of items that ends with some search criteria.
Example “robert” for the Author field
Query pattern
{ Field Name : { '$regex' : 'robert$' , '$options' : 'i' } }
Where ‘robert‘ is your search criteria
Example Query
filter = builder.Regex("Author", "robert"+ "$");
Above query, we have Author “Julia Robert” that matches with search criteria.
Scenarios 4 – C# Mongo Query Exact Match
Let’s look into regex exact Match MongoDB Query.
Query pattern
{ Author :{'$regex' : '^test$', '$options' : 'i'}}
Where ‘test’ is your search criteria
Example Query:
filter = builder.Regex("Author", "^" + search + "$");
Where ‘julia robert’ is our exact search criteria.
Here Author field value has to match exactly.
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.