Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-
typeofreturns JavaScript datatypes (string, number, boolean) -
$typereturns BSON datatypes (string, bool, int, double, objectId) - Use
$typefor 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.
Advertisements
