- 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 check if field is a number in MongoDB?
To check if field is a number in MongoDB, use the $type operator. Following is the syntax
db.yourCollectionName.find({youtFieldName: {$type:"number"}}).pretty();
Let us first create a collection with documents
> db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"John","StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec75dd628fa4220163b83") } >db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Chris","StudentMathScore":98,"StudentCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec77cd628fa4220163b84") } >db.checkIfFieldIsNumberDemo.insertOne({"StudentName":"Robert","StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec7a4d628fa4220163b85") } >db.checkIfFieldIsNumberDemo.insertOne({"StudentId":101,"StudentName":"Larry","StudentCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec7ccd628fa4220163b86") }
Following is the query to display all documents from a collection with the help of find() method
> db.checkIfFieldIsNumberDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c9ec75dd628fa4220163b83"), "StudentName" : "John", "StudentAge" : 23 } { "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "StudentName" : "Chris", "StudentMathScore" : 98, "StudentCountryName" : "US" } { "_id" : ObjectId("5c9ec7a4d628fa4220163b85"), "StudentName" : "Robert", "StudentCountryName" : "AUS" } { "_id" : ObjectId("5c9ec7ccd628fa4220163b86"), "StudentId" : 101, "StudentName" : "Larry", "StudentCountryName" : "AUS" }
Following is the query to check if a field is a number
> db.checkIfFieldIsNumberDemo.find({StudentMathScore: {$type:"number"}}).pretty();
The following is the output displaying the field which is a number i.e. StudentMathScore
{ "_id" : ObjectId("5c9ec77cd628fa4220163b84"), "StudentName" : "Chris", "StudentMathScore" : 98, "StudentCountryName" : "US" }
Advertisements
To Continue Learning Please Login
Login with Google