How to Run Like Queries in MongoDB
When working with textual data in mongodb, you may want to fetch documents with partial match on a field. You can use the $regex operator in mongodb for running like queries. By default, the like query using $regex is case sensitive.
Assume that you have collection in your mongodb containing names of the countries. A sample document from the countries collection is given below,
{ "countryName" : "United States", "isoCode" : "US", "countryCode" : "1" }
The following mongodb query fetches all documents where countryName contains "rab" anywhere. This query is the SQL equivalent of "%rab%".
db.getCollection('countries').find({'countryName': {'$regex': 'rab'}})
The above query returns documents for "United Arab Emirates" and "Saudi Arabia". But if you replace "rab" with "RAB", not document is returned. For doing a case-insensitive search, you need to use the $options for $regex as given below.
db.getCollection('countries').find({'countryName': {'$regex': 'RAB', '$options':'i'}})
The above query returns documents for "United Arab Emirates" and "Saudi Arabia" by doing a case-insensitive search.
Run the following query if you want to retrieve all the countries where the name starts with "In" by doing a case-insensitive search.
db.getCollection('countries').find({'countryName': {'$regex': '^In', '$options':'i'}})
Run the following query to retrieve all the countries where the name ends with "tes" by doing a case-insensitive search.
db.getCollection('countries').find({'countryName': {'$regex': "tes$" , '$options':'i'}})