How to change the type of a field in MongoDB?


Let us convert string type to int for an example. Aggregation does not allow us to directly change the type of a field; therefore, you need to write a code to convert the type of a field.

At first, create a collection with document. After that we will get the type of every field. The query to create a collection with document is as follows

>db.changeDataType.insertOne({"StudentName":"Larry","StudentAge":23,"StudentZipCode":"
10001","isProgrammer":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ed4976fd07954a4890694")
}

Display all documents from a collection with the help of find() method. The query is as follows:

> db.changeDataType.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6ed4976fd07954a4890694"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentZipCode" : "10001",
   "isProgrammer" : false
}

Now let us check type of every field in a collection. The query is as follows to check the type of every field:

> checkType=db.changeDataType.findOne();
{
   "_id" : ObjectId("5c6ed4976fd07954a4890694"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentZipCode" : "10001",
   "isProgrammer" : false
}

Now here we will use the above variable “checkType” to get the type of every variable. The query is as follows:

> typeof checkType._id;
object
> typeof checkType.StudentName;
string
> typeof checkType.StudentAge;
number
> typeof checkType.StudentZipCode;
string
> typeof checkType.isProgrammer;
boolean

Now, change the type of “StudentZipCode” from string to number type. The query is as follows:

> db.changeDataType.find().forEach(function(ch)
... {
... db.changeDataType.update({
... "_id":ch._id},
... {"$set":
... {
... "StudentZipCode":parseInt(ch.StudentZipCode)
... }
... });
... });

I have changed the type of “StudentZipCode” from string to number type. To verify, let us follow what we saw above to check the type of field in a collection:

> againCheckType=db.changeDataType.findOne();
{
   "_id" : ObjectId("5c6ed4976fd07954a4890694"),
   "StudentName" : "Larry",
   "StudentAge" : 23,
   "StudentZipCode" : 10001,
   "isProgrammer" : false
}

Use the above variable to check the type of field:

> typeof againCheckType.StudentZipCode;
number

Look at the above output now, the “StudentZipCode” field have been changed from String type to number.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements