Find which MongoDB document contains a specific string?

To find which document contains a specific string, use $regex along with find(). The regex operator performs pattern matching to locate documents containing the specified text substring.

Syntax

db.collection.find({
    fieldName: { $regex: /pattern/flags }
});

Sample Data

db.demo597.insertMany([
    { "Name": "John Doe" },
    { "Name": "John Smith" },
    { "Name": "Chris Brown" },
    { "Name": "Adam Smith" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e947ae3f5f1e70e134e2690"),
        ObjectId("5e947ae8f5f1e70e134e2691"),
        ObjectId("5e947aeff5f1e70e134e2692"),
        ObjectId("5e947afff5f1e70e134e2693")
    ]
}

Display All Documents

db.demo597.find();
{ "_id": ObjectId("5e947ae3f5f1e70e134e2690"), "Name": "John Doe" }
{ "_id": ObjectId("5e947ae8f5f1e70e134e2691"), "Name": "John Smith" }
{ "_id": ObjectId("5e947aeff5f1e70e134e2692"), "Name": "Chris Brown" }
{ "_id": ObjectId("5e947afff5f1e70e134e2693"), "Name": "Adam Smith" }

Example: Find Documents Containing "smith"

Find all documents where the Name field contains "smith" (case-insensitive) ?

db.demo597.find({
    Name: { $regex: /smith/i }
});
{ "_id": ObjectId("5e947ae8f5f1e70e134e2691"), "Name": "John Smith" }
{ "_id": ObjectId("5e947afff5f1e70e134e2693"), "Name": "Adam Smith" }

Key Points

  • The i flag makes the search case-insensitive.
  • Use /pattern/ for regex literals or "pattern" with $options.
  • $regex performs substring matching anywhere within the field value.

Conclusion

Use $regex with the i flag for case-insensitive string searching in MongoDB. This operator efficiently finds documents containing specific text patterns within field values.

Updated on: 2026-03-15T03:47:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements