• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:7 mins read
You are currently viewing MongoDB Change the Type of a Field

How to change the type of a field in MongoDB? In this article, we will explore different ways to change the type of field in MongoDB by using $convert, $toInt, $toDate, and $toString stage operators in db.collection.aggregation() method. The aggregation operators $toInt, $toDate, and $toString are the short forms of $convert.

Advertisements

Let’s consider the following collection student with documents where integer & date values are represented as string, hence these fields are required to change to the appropriate data type. For example, addmission field should be changed to Date type, the fees field should be changed to int e.t.c.


# Create Collection
db.student.insertMany([
      {  
         name: "Neutron",
         age: "20",
         marks: 98,
         addmission: "2020-09-15",
         fees: "5000",
         projectCompleted: "true"
         
      },
      {
         name: "Peter",
         age: "22",
         marks: 91,
         addmission: "2023-02-09",
         fees: "6000",
         projectCompleted: "true"
      }
   ]
)

We would be using the aggregate() method which takes the following syntax to change the types.


#aggregate()
db.collection.aggregate( [ { <stage> }, ... ] )
#or
db.aggregate( [ { <stage> }, ... ] )

1. Using $toInt Operator to Change Type of Field

You can use the MongoDB db.collection.aggregation() method along with the $addFields stage and $toInt aggregation operator to convert a field from a string type to an integer type. This operator parses the string and converts it to an integer.


# Usage of $addFields stage with $toInt operator
db.student.aggregate([
  {
    $addFields: {
      fees: { $toInt: "$fees" }
    }
  }
])

Here, we have used the aggregation pipeline with the $addFields stage which adds a new field fees to each document (actually replaces existing field) in the student collection by changing the field type from string to int by using the $toInt aggregation operator.

The output shows the documents with the fees field having integer values of int type.

Change Field type in MongoDB

2. Using $toDate aggregation operator to change to Date type

To change a string field that contains a date to a date type, use the $toDate operator. The field admission is stored with the date value but as a string type in all the documents of the collection student, Here, I will change it to date type, so that we can easily query using date type.

Now, consider the following query where the aggregation pipeline uses the $project stage which reshapes the documents by adding a new field addmissionDate. Then, we have $toDate aggregation operator which transforms the admission field from a string data type to a date data type.


# Usage of $toDate Aggregation stage
db.student.aggregate([
  {
    $project: {
      addmissionDate: {
        $toDate: "$addmission"
      }
    }
  }
])

The output here displayed the new field addmissionDate with the date values in an ISODate format.

Change Field type in MongoDB

3. Using $toString aggregation operator to change to String type

We are often required to change the type of a field to a string, you can use the MongoDB $toString aggregation operator to convert a non-string field to a string field. For example, you can easily convert field types from an integer, date, or Boolean to String type.

For example, the marks field of all our documents in the collection student contains the integer type. Let’s convert this field from integer to string type. In this case, the $project stage adds a new field marksString. Then, we called the $toString operator within the marksString which converts the marks field from a numeric data type to a string data type.


# Usage of $toString Aggregation stage
db.student.aggregate([
  {
    $project: {
      marksString: {
        $toString: "$marks"
      }
    }
  }
])

Yields below output.

4. Using $toConvert aggregation operator to change to any type

You can also use the $convert aggregation operator for converting the data type of a field in MongoDB. This operator is very effective and can convert a field to any data type, or it can convert a field to null if the conversion is not possible.

For example, we have a field age in the documents which is a string type. Now, we use the $toConvert operator to change it to an integer type.


# Usage of $toConvert Aggregation stage
db.student.aggregate([
  {
    $project: {
     _id: 1,
      age: {
        $convert: {
          input: "$age",
          to: "int"
        }
      }
    }
  },
  {
    $out: "student"
  }
])

In the above example, we have first added the new field age that is converted to an integer data type by using the $toConvert operator. Here, we change the age field from a string data type to an integer data type. The input parameter specifies the source field to convert, and the to parameter specifies the target data type. Lastly, we have an $out operator that overwrites the existing collection student with the new one.

Change Field type in MongoDB

5. Conclusion

In this article, you have learned how to can change the type of field in MongoDB by using the aggregate() method and the $convert aggregation operator. The other examples we have explored in this article demonstrated some of MongoDB’s most common scenarios for changing field types.