MongoDB regular expression to fetch record with specific name "John", instead of "john

To fetch records with a specific case-sensitive name using MongoDB regular expressions, use the exact pattern match syntax /searchWord/. By default, MongoDB regex is case-sensitive, so /John/ will match "John" but not "john".

Syntax

db.collection.find({"field": /exactPattern/});

Sample Data

db.demo221.insertMany([
    {"Details": {"StudentName": "Chris", "StudentAge": 21}},
    {"Details": {"StudentName": "John", "StudentAge": 20}},
    {"Details": {"StudentName": "Bob", "StudentAge": 22}},
    {"Details": {"StudentName": "john", "StudentAge": 24}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3ee15d03d395bdc213472b"),
        ObjectId("5e3ee16503d395bdc213472c"),
        ObjectId("5e3ee16b03d395bdc213472d"),
        ObjectId("5e3ee17303d395bdc213472e")
    ]
}

Display All Documents

db.demo221.find();
{ "_id": ObjectId("5e3ee15d03d395bdc213472b"), "Details": { "StudentName": "Chris", "StudentAge": 21 } }
{ "_id": ObjectId("5e3ee16503d395bdc213472c"), "Details": { "StudentName": "John", "StudentAge": 20 } }
{ "_id": ObjectId("5e3ee16b03d395bdc213472d"), "Details": { "StudentName": "Bob", "StudentAge": 22 } }
{ "_id": ObjectId("5e3ee17303d395bdc213472e"), "Details": { "StudentName": "john", "StudentAge": 24 } }

Example: Case-Sensitive Search for "John"

To fetch only records with the exact case "John" (not "john") ?

db.demo221.find({"Details.StudentName": /John/});
{ "_id": ObjectId("5e3ee16503d395bdc213472c"), "Details": { "StudentName": "John", "StudentAge": 20 } }

Key Points

  • MongoDB regex /John/ is case-sensitive by default
  • Matches only "John" but excludes "john", "JOHN", or other case variations
  • Use /john/i flag for case-insensitive matching if needed

Conclusion

MongoDB regular expressions provide precise case-sensitive matching using /pattern/ syntax. This allows filtering records with exact string cases, distinguishing between "John" and "john" effectively.

Updated on: 2026-03-15T01:59:23+05:30

141 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements