Query MongoDB with "like" implementation on name and email field beginning with a specific letter?

To implement "like" functionality in MongoDB, use regular expressions with the /pattern/ syntax. For matching fields beginning with a specific letter, use the ^ anchor followed by the letter.

Syntax

db.collection.find({
    "$or": [
        { "fieldName1": /^letter/ },
        { "fieldName2": /^letter/ }
    ]
});

Sample Data

db.demo554.insertMany([
    { "UserName": "John", "UserMailId": "John@gmail.com" },
    { "UserName": "Chris", "UserMailId": "Chris@gmail.com" },
    { "UserName": "Jace", "UserMailId": "Jace@gmail.com" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e8f1cfed1d72c4545cb8679"),
        ObjectId("5e8f1d0cd1d72c4545cb867a"),
        ObjectId("5e8f1d1cd1d72c4545cb867b")
    ]
}

Display All Documents

db.demo554.find();
{ "_id": ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName": "John", "UserMailId": "John@gmail.com" }
{ "_id": ObjectId("5e8f1d0cd1d72c4545cb867a"), "UserName": "Chris", "UserMailId": "Chris@gmail.com" }
{ "_id": ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName": "Jace", "UserMailId": "Jace@gmail.com" }

Example: Find Documents Beginning with "J"

Query documents where UserName or UserMailId begins with the letter "J":

db.demo554.find({
    "$or": [
        { "UserName": /^J/ },
        { "UserMailId": /^J/ }
    ]
});
{ "_id": ObjectId("5e8f1cfed1d72c4545cb8679"), "UserName": "John", "UserMailId": "John@gmail.com" }
{ "_id": ObjectId("5e8f1d1cd1d72c4545cb867b"), "UserName": "Jace", "UserMailId": "Jace@gmail.com" }

Key Points

  • Use /^letter/ to match fields beginning with a specific letter
  • The ^ anchor ensures matching only at the start of the string
  • $or operator searches across multiple fields simultaneously
  • Regular expressions in MongoDB are case-sensitive by default

Conclusion

MongoDB's regular expression support with /^letter/ syntax provides powerful "like" functionality. Use $or to search across multiple fields for comprehensive text matching.

Updated on: 2026-03-15T03:33:19+05:30

985 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements