How to select only numeric strings in MongoDB?


Let us create a collection with documents −

> db.selectOnlyNumericDemo.insertOne({"UserId":"User101"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb711de8cc557214c0e16")
}
> db.selectOnlyNumericDemo.insertOne({"UserId":"102"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb716de8cc557214c0e17")
}
> db.selectOnlyNumericDemo.insertOne({"UserId":"User103"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb71dde8cc557214c0e18")
}
> db.selectOnlyNumericDemo.insertOne({"UserId":"104"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdb725de8cc557214c0e19")
}

Display all documents from a collection with the help of find() method −

> db.selectOnlyNumericDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5cbdb711de8cc557214c0e16"), "UserId" : "User101" }
{ "_id" : ObjectId("5cbdb716de8cc557214c0e17"), "UserId" : "102" }
{ "_id" : ObjectId("5cbdb71dde8cc557214c0e18"), "UserId" : "User103" }
{ "_id" : ObjectId("5cbdb725de8cc557214c0e19"), "UserId" : "104" }

Following is the query to select only numeric strings or check whether string is numeric in MongoDB −

> db.selectOnlyNumericDemo.find({'UserId': /^\d+$/});

This will produce the following output −

{ "_id" : ObjectId("5cbdb716de8cc557214c0e17"), "UserId" : "102" }
{ "_id" : ObjectId("5cbdb725de8cc557214c0e19"), "UserId" : "104" }

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements