Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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/ipattern 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.
Advertisements
