MongoDB Regex Search on Integer Value?

To perform regex search on integer values in MongoDB, use the $where operator with JavaScript regex testing. This allows pattern matching on numeric fields by converting them to strings during evaluation.

Syntax

db.collection.find({ 
    $where: "/^yourPattern.*/.test(this.fieldName)" 
});

Sample Data

db.regExpOnIntegerDemo.insertMany([
    { "StudentId": 2341234 },
    { "StudentId": 123234 },
    { "StudentId": 9871234 },
    { "StudentId": 2345612 },
    { "StudentId": 1239812345 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c70370c75eb1743ddddce21"),
        ObjectId("5c70371175eb1743ddddce22"),
        ObjectId("5c70371875eb1743ddddce23"),
        ObjectId("5c70372275eb1743ddddce24"),
        ObjectId("5c70372975eb1743ddddce25")
    ]
}

Display all documents to verify the data ?

db.regExpOnIntegerDemo.find().pretty();
{ "_id": ObjectId("5c70370c75eb1743ddddce21"), "StudentId": 2341234 }
{ "_id": ObjectId("5c70371175eb1743ddddce22"), "StudentId": 123234 }
{ "_id": ObjectId("5c70371875eb1743ddddce23"), "StudentId": 9871234 }
{ "_id": ObjectId("5c70372275eb1743ddddce24"), "StudentId": 2345612 }
{ "_id": ObjectId("5c70372975eb1743ddddce25"), "StudentId": 1239812345 }

Example: Find StudentIds Starting with "123"

db.regExpOnIntegerDemo.find({ 
    $where: "/^123.*/.test(this.StudentId)" 
});
{ "_id": ObjectId("5c70371175eb1743ddddce22"), "StudentId": 123234 }
{ "_id": ObjectId("5c70372975eb1743ddddce25"), "StudentId": 1239812345 }

How It Works

The $where operator executes JavaScript expressions where this refers to the current document. The regex /^123.*/ matches any number starting with "123", and .test() returns true for matching documents.

Key Points

  • $where is slower than standard operators as it executes JavaScript
  • The integer is automatically converted to string for regex testing
  • Use ^ for start-of-string matching and .* for any following characters

Conclusion

Use $where with JavaScript regex to search integer patterns in MongoDB. While effective, consider performance implications and use standard operators when possible for better efficiency.

Updated on: 2026-03-14T23:56:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements