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
Using regex in MongoDB findOne()
The findOne() method returns the first document that matches the specified query criteria in a MongoDB collection. When combined with regular expressions, it provides powerful text matching capabilities for pattern-based searches.
Syntax
db.collection.findOne({field: {$regex: /pattern/flags}})
Sample Data
Let's create a collection with sample documents ?
db.demo655.insertMany([
{subject: "MySQL"},
{subject: "MongoDB"},
{subject: "Java"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea050254deddd72997713cc"),
ObjectId("5ea0502b4deddd72997713cd"),
ObjectId("5ea050314deddd72997713ce")
]
}
Display all documents from the collection ?
db.demo655.find();
{ "_id": ObjectId("5ea050254deddd72997713cc"), "subject": "MySQL" }
{ "_id": ObjectId("5ea0502b4deddd72997713cd"), "subject": "MongoDB" }
{ "_id": ObjectId("5ea050314deddd72997713ce"), "subject": "Java" }
Example: Find First Document Starting with "M"
Use regex to find the first document where the subject field starts with the letter "M" ?
db.demo655.findOne({subject: {$regex: /^M/}});
{ "_id": ObjectId("5ea050254deddd72997713cc"), "subject": "MySQL" }
Case-Insensitive Search
Use the i flag for case-insensitive matching ?
db.demo655.findOne({subject: {$regex: /mongo/i}});
{ "_id": ObjectId("5ea0502b4deddd72997713cd"), "subject": "MongoDB" }
Key Points
-
findOne()returns only the first matching document, even if multiple documents match the regex pattern. - Use
^to match the beginning and$to match the end of strings. - The
iflag enables case-insensitive matching.
Conclusion
Regular expressions with findOne() provide flexible pattern matching for document retrieval. The $regex operator enables powerful text searches while findOne() ensures only the first match is returned.
Advertisements
