Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to query MongoDB with LIKE?
MongoDB does not have a LIKE operator like SQL. Instead, use regular expressions (regex) or the $regex operator for pattern matching.
Syntax
// Using regex literal (equivalent to SQL LIKE '%value%')
db.collection.find({"field": /.*value.*/})
// Using $regex operator
db.collection.find({"field": {$regex: "value", $options: "i"}})
Create Sample Data
db.employee.insertMany([
{"EmployeeName": "John", "EmployeeSalary": 450000},
{"EmployeeName": "Carol", "EmployeeSalary": 150000},
{"EmployeeName": "James", "EmployeeSalary": 550000},
{"EmployeeName": "Jace", "EmployeeSalary": 670000},
{"EmployeeName": "Larry", "EmployeeSalary": 1000000}
]);
Query with "like" Using Regex
Find all employees whose name contains "J" ?
db.employee.find({"EmployeeName": /.*J.*/}).pretty();
{ "EmployeeName": "John", "EmployeeSalary": 450000 }
{ "EmployeeName": "James", "EmployeeSalary": 550000 }
{ "EmployeeName": "Jace", "EmployeeSalary": 670000 }
Common Patterns
| SQL LIKE | MongoDB Regex | Description |
|---|---|---|
LIKE '%value%' |
/value/ or /.*value.*/
|
Contains "value" |
LIKE 'value%' |
/^value/ |
Starts with "value" |
LIKE '%value' |
/value$/ |
Ends with "value" |
LIKE 'value' (case-insensitive) |
/value/i |
Case-insensitive match |
Examples
// Starts with "J"
db.employee.find({"EmployeeName": /^J/});
// Ends with "y"
db.employee.find({"EmployeeName": /y$/});
// Case-insensitive contains "ja"
db.employee.find({"EmployeeName": /ja/i});
// Using $regex operator
db.employee.find({"EmployeeName": {$regex: "^J", $options: "i"}});
Conclusion
Use regex literals (/pattern/) or the $regex operator for SQL LIKE-equivalent queries in MongoDB. Use ^ for starts-with, $ for ends-with, and the i flag for case-insensitive matching.
Advertisements
