Toggle website search
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
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.
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.