How to use LIKE operator in mongodb to match some pattern?
meda Changed status to publish 16/07/2022
LIKE operator in other relational database is mostly used to match patterns. This operator can be used with wildcard operators like modulo(%) and underscore(_). The modulo sign represents zero or more characters/numbers whereas the underscore represents exactly one character/number.
SELECT * FROM customers WHERE customerName LIKE '%mas' //Anything that end with 'mas' e.g Tomas SELECT * FROM customers WHERE customerName LIKE '%nal%' //Anthing that contains 'nal' in the middle e.g Ronaldo SELECT * FROM customers WHERE customerName LIKE '_omas' //This expects just one character e.g Tomas
In MongoDB, We can achieve similar way in a different syntax, either by using regex or other simpler ones.
db.customers.find({customerName: /mas$/}) db.customers.find({customerName: {'$regex': 'mas$', '$options': 'i'}}) ##Anything that end with 'mas' e.g Tomas db.customers.find({customerName: /^mas/}) db.customers.find({customerName: {'$regex': '^mas', '$options': 'i'}}) ##Anything that starts with 'mas' e.g Mason db.customers.find({customerName: /nal/}) db.customers.find({customerName: {'$regex': 'nal', '$options': 'i'}}) ##Anthing that contains 'nal' in the middle e.g Ronaldo
mesihg Changed status to publish 28/02/2022