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
How to query an Array[String] for a Regular Expression match?
To query an array of strings for a regular expression match in MongoDB, use the regular expression pattern directly in the find query. MongoDB automatically searches through array elements and matches any string that satisfies the regex pattern.
Syntax
db.collection.find({ arrayField: /regexPattern/ })
Create Sample Data
db.queryArrayDemo.insertMany([
{
"StudentFullName": [
"Carol Taylor",
"Caroline Williams",
"Claire Brown"
]
},
{
"StudentFullName": [
"John Smith",
"Jace Doe",
"Jabin Brown"
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ca2774c6304881c5ce84ba0"),
ObjectId("5ca277b36304881c5ce84ba1")
]
}
Display All Documents
db.queryArrayDemo.find().pretty()
{
"_id": ObjectId("5ca2774c6304881c5ce84ba0"),
"StudentFullName": [
"Carol Taylor",
"Caroline Williams",
"Claire Brown"
]
}
{
"_id": ObjectId("5ca277b36304881c5ce84ba1"),
"StudentFullName": [
"John Smith",
"Jace Doe",
"Jabin Brown"
]
}
Example: Query Array with Regex Match
Find documents where any array element starts with "J" ?
db.queryArrayDemo.find({ StudentFullName: /^J/ })
{
"_id": ObjectId("5ca277b36304881c5ce84ba1"),
"StudentFullName": [
"John Smith",
"Jace Doe",
"Jabin Brown"
]
}
More Examples
Case-Insensitive Search
db.queryArrayDemo.find({ StudentFullName: /carol/i })
Contains Pattern
db.queryArrayDemo.find({ StudentFullName: /Brown/ })
Conclusion
MongoDB automatically searches through array elements when using regex patterns. Use /^pattern/ for starts-with matching and /pattern/i for case-insensitive searches across string arrays.
Advertisements
