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.

Updated on: 2026-03-15T00:47:34+05:30

170 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements