How to find datatype of all the fields in MongoDB?

MongoDBDatabaseBig Data Analytics

Use typeof to find datatype of all the fields −

typeof db.yourCollectionName.findOne().yourFieldName;

Let us first create a collection with documents −

> db.findDataTypeDemo.insertOne({"ClientName":"Chris","isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccf2064dceb9a92e6aa1952")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.findDataTypeDemo.findOne();

This will produce the following output −

{
   "_id" : ObjectId("5ccf2064dceb9a92e6aa1952"),
   "ClientName" : "Chris",
   "isMarried" : false
}

Following is the query to find datatype of a field in MongoDB −

> typeof db.findDataTypeDemo.findOne().isMarried;

This will produce the following output −

Boolean

Here is the query to get the data type of another field −

> typeof db.findDataTypeDemo.findOne().ClientName;

This will produce the following output −

String

You can get the value also. The query is as follows −

> db.findDataTypeDemo.findOne().ClientName;
Chris
> db.findDataTypeDemo.findOne().isMarried;
False
raja
Published on 22-May-2019 11:11:54
Advertisements