Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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" }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.