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