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
-
Economics & Finance
Selected Reading
Finding matching records with LIKE in MongoDB?
To perform LIKE operations in MongoDB, use regular expressions (regex) with the find() method. MongoDB doesn't have a LIKE operator like SQL, but regex patterns provide equivalent functionality for pattern matching in text fields.
Syntax
db.collection.find({ "field": /pattern/flags })
Common patterns:
-
/^text/- Starts with "text" -
/text$/- Ends with "text" -
/text/- Contains "text" -
/text/i- Case-insensitive matching
Sample Data
db.likeDemo.insertMany([
{"Name": "John", "Age": 32},
{"Name": "Chris", "Age": 25},
{"Name": "Carol", "Age": 22},
{"Name": "Johnny", "Age": 22},
{"Name": "James", "Age": 27}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cb84984623186894665ae41"),
ObjectId("5cb84991623186894665ae42"),
ObjectId("5cb849a1623186894665ae43"),
ObjectId("5cb849b2623186894665ae44"),
ObjectId("5cb849bb623186894665ae45")
]
}
Display All Documents
db.likeDemo.find().pretty();
{
"_id": ObjectId("5cb84984623186894665ae41"),
"Name": "John",
"Age": 32
}
{
"_id": ObjectId("5cb84991623186894665ae42"),
"Name": "Chris",
"Age": 25
}
{
"_id": ObjectId("5cb849a1623186894665ae43"),
"Name": "Carol",
"Age": 22
}
{
"_id": ObjectId("5cb849b2623186894665ae44"),
"Name": "Johnny",
"Age": 22
}
{
"_id": ObjectId("5cb849bb623186894665ae45"),
"Name": "James",
"Age": 27
}
Example: Names Starting with "Jo"
db.likeDemo.find({Name: /^Jo/i}).pretty();
{
"_id": ObjectId("5cb84984623186894665ae41"),
"Name": "John",
"Age": 32
}
{
"_id": ObjectId("5cb849b2623186894665ae44"),
"Name": "Johnny",
"Age": 22
}
Conclusion
MongoDB uses regex patterns instead of SQL's LIKE operator. Use /^pattern/ for starts with, /pattern$/ for ends with, and /pattern/i for case-insensitive matching to achieve LIKE functionality.
Advertisements
