- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }
Advertisements