How to select only numeric strings in MongoDB?

To select only numeric strings in MongoDB, use regular expressions with the pattern /^\d+$/ which matches strings containing only digits from start to end.

Syntax

db.collection.find({ "field": /^\d+$/ });

Sample Data

db.selectOnlyNumericDemo.insertMany([
    { "UserId": "User101" },
    { "UserId": "102" },
    { "UserId": "User103" },
    { "UserId": "104" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cbdb711de8cc557214c0e16"),
        ObjectId("5cbdb716de8cc557214c0e17"),
        ObjectId("5cbdb71dde8cc557214c0e18"),
        ObjectId("5cbdb725de8cc557214c0e19")
    ]
}

Display all documents to see the test data ?

db.selectOnlyNumericDemo.find().pretty();
{ "_id": ObjectId("5cbdb711de8cc557214c0e16"), "UserId": "User101" }
{ "_id": ObjectId("5cbdb716de8cc557214c0e17"), "UserId": "102" }
{ "_id": ObjectId("5cbdb71dde8cc557214c0e18"), "UserId": "User103" }
{ "_id": ObjectId("5cbdb725de8cc557214c0e19"), "UserId": "104" }

Example: Select Only Numeric Strings

Use the regular expression /^\d+$/ to find documents where the field contains only numeric characters ?

db.selectOnlyNumericDemo.find({ "UserId": /^\d+$/ });
{ "_id": ObjectId("5cbdb716de8cc557214c0e17"), "UserId": "102" }
{ "_id": ObjectId("5cbdb725de8cc557214c0e19"), "UserId": "104" }

How It Works

  • ^ − Matches the beginning of the string
  • \d − Matches any digit (0-9)
  • + − Matches one or more digits
  • $ − Matches the end of the string

This pattern ensures the entire string contains only numeric characters, excluding mixed alphanumeric strings like "User101".

Conclusion

Use the regex pattern /^\d+$/ to filter documents containing only numeric strings. This method effectively distinguishes pure numeric strings from mixed alphanumeric values in MongoDB collections.

Updated on: 2026-03-15T00:51:34+05:30

590 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements