MongoDB query to display documents with a specific name irrespective of case

To display documents with a specific name irrespective of case in MongoDB, use the $regex operator with the i flag for case-insensitive matching. This allows you to find documents containing a specific string value regardless of uppercase or lowercase letters.

Syntax

db.collection.find({
    "field": { $regex: /pattern/i }
});

Sample Data

db.demo700.insertMany([
    { details: [{ Name: "david" }] },
    { details: [{ Name: "Chris" }] },
    { details: [{ Name: "DAVID" }] },
    { details: [{ Name: "David" }] }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ea6e6b1551299a9f98c93ac"),
        ObjectId("5ea6e6b9551299a9f98c93ad"),
        ObjectId("5ea6e6bf551299a9f98c93ae"),
        ObjectId("5ea6e6c4551299a9f98c93af")
    ]
}

Display all documents from the collection ?

db.demo700.find();
{ "_id": ObjectId("5ea6e6b1551299a9f98c93ac"), "details": [{ "Name": "david" }] }
{ "_id": ObjectId("5ea6e6b9551299a9f98c93ad"), "details": [{ "Name": "Chris" }] }
{ "_id": ObjectId("5ea6e6bf551299a9f98c93ae"), "details": [{ "Name": "DAVID" }] }
{ "_id": ObjectId("5ea6e6c4551299a9f98c93af"), "details": [{ "Name": "David" }] }

Example: Case-Insensitive Search

Find all documents with "David" in any case variation ?

db.demo700.find({
    "details.Name": { $regex: /^David$/i }
});
{ "_id": ObjectId("5ea6e6b1551299a9f98c93ac"), "details": [{ "Name": "david" }] }
{ "_id": ObjectId("5ea6e6bf551299a9f98c93ae"), "details": [{ "Name": "DAVID" }] }
{ "_id": ObjectId("5ea6e6c4551299a9f98c93af"), "details": [{ "Name": "David" }] }

Key Points

  • The ^ symbol ensures matching from the beginning of the string
  • The $ symbol ensures matching to the end of the string
  • The i flag makes the regex case-insensitive
  • Use dot notation like "details.Name" to search within nested arrays

Conclusion

The $regex operator with the i flag provides powerful case-insensitive string matching in MongoDB. Combined with anchors ^ and $, it enables exact case-insensitive searches within document fields.

Updated on: 2026-03-15T03:39:45+05:30

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements