Query in MongoDB to perform an operation similar to LIKE operation

MongoDB doesn't have a direct LIKE operator, but you can achieve similar functionality using regular expressions with the /pattern/ syntax or the $regex operator for pattern matching in string fields.

Syntax

// Using regex pattern
db.collection.find({"field": /pattern/})

// Using $regex operator
db.collection.find({"field": {$regex: "pattern"}})

Sample Data

db.demo26.insertMany([
    {"StudentName": "Chris"},
    {"StudentName": "John"},
    {"StudentName": "Jones"},
    {"StudentName": "David"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e14c9dc22d07d3b95082e79"),
        ObjectId("5e14c9e022d07d3b95082e7a"),
        ObjectId("5e14ca7222d07d3b95082e7b"),
        ObjectId("5e14ca7622d07d3b95082e7c")
    ]
}

Display all documents from the collection ?

db.demo26.find();
{ "_id": ObjectId("5e14c9dc22d07d3b95082e79"), "StudentName": "Chris" }
{ "_id": ObjectId("5e14c9e022d07d3b95082e7a"), "StudentName": "John" }
{ "_id": ObjectId("5e14ca7222d07d3b95082e7b"), "StudentName": "Jones" }
{ "_id": ObjectId("5e14ca7622d07d3b95082e7c"), "StudentName": "David" }

Example: Find Names Containing "Jo"

Find all students whose names contain "Jo" using regex pattern ?

db.demo26.find({"StudentName": /Jo/});
{ "_id": ObjectId("5e14c9e022d07d3b95082e7a"), "StudentName": "John" }
{ "_id": ObjectId("5e14ca7222d07d3b95082e7b"), "StudentName": "Jones" }

Common Pattern Examples

// Starts with "Jo" (LIKE 'Jo%')
db.demo26.find({"StudentName": /^Jo/});

// Ends with "es" (LIKE '%es')
db.demo26.find({"StudentName": /es$/});

// Case-insensitive search (LIKE '%jo%')
db.demo26.find({"StudentName": /jo/i});

Conclusion

Use regular expressions with /pattern/ syntax to perform LIKE operations in MongoDB. The ^ symbol matches the beginning, $ matches the end, and i flag enables case-insensitive matching.

Updated on: 2026-03-15T02:38:48+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements