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
How to change the type of a field in MongoDB?
MongoDB allows you to change the data type of existing fields using update operations with type conversion functions. Let us convert a string type field to number type using the parseInt() function with an update query.
Sample Data
First, create a collection with a document containing different data types ?
db.changeDataType.insertOne({
"StudentName": "Larry",
"StudentAge": 23,
"StudentZipCode": "10001",
"isProgrammer": false
});
{
"acknowledged": true,
"insertedId": ObjectId("5c6ed4976fd07954a4890694")
}
Display the document to verify the data ?
db.changeDataType.find().pretty();
{
"_id": ObjectId("5c6ed4976fd07954a4890694"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentZipCode": "10001",
"isProgrammer": false
}
Check Current Field Types
Use the typeof operator to check the current data types of each field ?
checkType = db.changeDataType.findOne(); typeof checkType._id; typeof checkType.StudentName; typeof checkType.StudentAge; typeof checkType.StudentZipCode; typeof checkType.isProgrammer;
object string number string boolean
Convert String to Number Type
Now change the StudentZipCode field from string to number type using forEach() and parseInt() ?
db.changeDataType.find().forEach(function(doc) {
db.changeDataType.update(
{"_id": doc._id},
{"$set": {
"StudentZipCode": parseInt(doc.StudentZipCode)
}}
);
});
Verify the Type Change
Check the updated document and verify the data type conversion ?
updatedDoc = db.changeDataType.findOne();
{
"_id": ObjectId("5c6ed4976fd07954a4890694"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentZipCode": 10001,
"isProgrammer": false
}
Confirm the type change ?
typeof updatedDoc.StudentZipCode;
number
Conclusion
MongoDB doesn't support direct field type conversion, but you can change field types by updating documents with type conversion functions like parseInt(), parseFloat(), or toString() using the $set operator.
