How to find datatype of all the fields in MongoDB?

To find the datatype of all fields in MongoDB, use the typeof operator with findOne() to check individual field types, or use aggregation pipeline to analyze multiple fields systematically.

Syntax

typeof db.collectionName.findOne().fieldName;

Sample Data

Let us first create a collection with documents ?

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

Display the document to see all fields ?

db.findDataTypeDemo.findOne();
{
    "_id": ObjectId("5ccf2064dceb9a92e6aa1952"),
    "ClientName": "Chris",
    "isMarried": false,
    "age": 25,
    "salary": 50000.5
}

Method 1: Using typeof for Individual Fields

Check the datatype of the boolean field ?

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

Check the datatype of the string field ?

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

Check the datatype of numeric fields ?

typeof db.findDataTypeDemo.findOne().age;
typeof db.findDataTypeDemo.findOne().salary;
number
number

Method 2: Using Aggregation Pipeline

Get all field types systematically using $type operator ?

db.findDataTypeDemo.aggregate([
    {
        $project: {
            ClientNameType: { $type: "$ClientName" },
            isMarriedType: { $type: "$isMarried" },
            ageType: { $type: "$age" },
            salaryType: { $type: "$salary" }
        }
    }
]);
{
    "_id": ObjectId("5ccf2064dceb9a92e6aa1952"),
    "ClientNameType": "string",
    "isMarriedType": "bool",
    "ageType": "int",
    "salaryType": "double"
}

Key Points

  • typeof returns JavaScript datatypes (string, number, boolean)
  • $type returns BSON datatypes (string, bool, int, double, objectId)
  • Use $type for more precise MongoDB-specific type information

Conclusion

Use typeof for quick field type checks or $type in aggregation for detailed BSON type analysis. The aggregation approach is more efficient for checking multiple fields simultaneously.

Updated on: 2026-03-15T00:58:12+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements