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 i flag 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.

Updated on: 2026-03-15T03:25:20+05:30

706 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements