MongoDB: Find name similar to Regular Expression input?

To find names similar to a regular expression input in MongoDB, use the $regex operator with the $options parameter for case-insensitive matching.

Syntax

db.collection.find({
    "fieldName": {
        $regex: "pattern",
        $options: "i"
    }
});

Sample Data

db.demo514.insertMany([
    {"Information": {"FullName": "John Doe"}},
    {"Information": {"FullName": "John Smith"}},
    {"Information": {"FullName": "john doe"}},
    {"Information": {"FullName": "Chris Brown"}}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e885116987b6e0e9d18f58c"),
        ObjectId("5e88515e987b6e0e9d18f58d"),
        ObjectId("5e885169987b6e0e9d18f58e"),
        ObjectId("5e88516f987b6e0e9d18f58f")
    ]
}

Display All Documents

db.demo514.find();
{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e88515e987b6e0e9d18f58d"), "Information" : { "FullName" : "John Smith" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }
{ "_id" : ObjectId("5e88516f987b6e0e9d18f58f"), "Information" : { "FullName" : "Chris Brown" } }

Example: Find Names Similar to "John Doe"

db.demo514.find({
    "Information.FullName": {
        $regex: "John Doe",
        $options: "i"
    }
});
{ "_id" : ObjectId("5e885116987b6e0e9d18f58c"), "Information" : { "FullName" : "John Doe" } }
{ "_id" : ObjectId("5e885169987b6e0e9d18f58e"), "Information" : { "FullName" : "john doe" } }

Key Points

  • The $options: "i" parameter makes the search case-insensitive
  • Use dot notation to access nested fields like "Information.FullName"
  • $regex supports partial matching and pattern-based searches

Conclusion

The $regex operator with $options: "i" enables flexible, case-insensitive name matching in MongoDB. This approach is ideal for user search functionality where exact case matching isn't required.

Updated on: 2026-03-15T03:21:28+05:30

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements