How to check the type of a field in Mongo shell

Check the type of a field in Mongo shell :

We can check the type of a field using Mongo shell. In this quick tutorial, I will show you how to do that. MongoDB provides two different operators for type checking: instanceof and typeof. Using these operators, we can either check if a field is of a certain type or we can check the type of a field. Let me show with two examples to make this more clear :

Instanceof and typeof example :

First of all, let’s insert some data to the to a collection :

> use Students
switched to db Students
> db.list.insertOne({
   name : "Albert",
   age : 22,
   marks : { physics : 77.5, chemistry : 89 }
  })
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5b6db2b260f6ba4354f64203")
}
> db.list.find()
{ "_id" : ObjectId("5b6db2b260f6ba4354f64203"), "name" : "Albert", "age" : 22, "marks" : { "physics" :
 77.5, "chemistry" : 89 } }
>

mongo check value type

instanceof returns a boolean value if the result is true. For example, let’s try to check few values of the above document :

db.list.name instanceof Object

It will return true. Similarly, we can use typeof to print the type of a field like below :

typeof db.list.marks.physics

It will print object. mongo check value type