Finding a MongoDB document through a word

To find a MongoDB document through a word, use the find() method with regular expression pattern matching. The /word/i syntax performs case-insensitive search for the specified word within field values.

Syntax

db.collection.find({
    "fieldName": /searchWord/i
});

Create Sample Data

db.demo212.insertMany([
    {"details": [{"Name": "John Doe"}]},
    {"details": [{"Name": "Chris Brown"}]},
    {"details": [{"Name": "Robert doe"}]}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3e2c7603d395bdc21346ff"),
        ObjectId("5e3e2c8003d395bdc2134700"),
        ObjectId("5e3e2c8a03d395bdc2134701")
    ]
}

Display All Documents

db.demo212.find();
{ "_id": ObjectId("5e3e2c7603d395bdc21346ff"), "details": [{"Name": "John Doe"}] }
{ "_id": ObjectId("5e3e2c8003d395bdc2134700"), "details": [{"Name": "Chris Brown"}] }
{ "_id": ObjectId("5e3e2c8a03d395bdc2134701"), "details": [{"Name": "Robert doe"}] }

Example: Find Documents Containing "doe"

Search for documents where the nested Name field contains the word "doe" (case-insensitive) ?

db.demo212.find({"details.Name": /doe/i});
{ "_id": ObjectId("5e3e2c7603d395bdc21346ff"), "details": [{"Name": "John Doe"}] }
{ "_id": ObjectId("5e3e2c8a03d395bdc2134701"), "details": [{"Name": "Robert doe"}] }

Key Points

  • The /word/i pattern performs case-insensitive matching
  • Use dot notation to search within nested array fields
  • Regular expressions match partial words within the field value

Conclusion

Use regular expression patterns with the /i flag in MongoDB queries to perform case-insensitive word searches. This method efficiently finds documents containing specific words regardless of capitalization.

Updated on: 2026-03-15T01:45:15+05:30

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements