Introduction to MongoDB $convert Operator

$convert is an aggregation pipeline operator in MongoDB that converts one data type to another data type. The data types that can be converted include numeric types, date types, string types, etc.

Syntax

The syntax of the $convert operator is as follows:

{ $convert: { input: <expression>, to: <type>, onError: <expression>, onNull: <expression> } }

The input parameter represents the value to be converted; the to parameter represents the target data type to be converted to, which can be one of the following types: double, string, objectId, bool, date, int, long; the onError and onNull parameters are optional and represent the values to be returned when an error is encountered during conversion or the input is null.

Use Cases

The $convert operator is commonly used in aggregation pipelines to perform type conversions on data to meet business requirements. For example, for date type data, $convert can be used to convert it to string type, making it easier to output and process data.

Example

Suppose we have the following document collection students:

{ "_id" : 1, "name" : "Tom", "age" : "22" }
{ "_id" : 2, "name" : "Jerry", "age" : "23" }
{ "_id" : 3, "name" : "Bob", "age" : "25" }
{ "_id" : 4, "name" : "Alice", "age" : "21" }

Where the age field is of string type, and we need to convert it to numeric type.

We can use the following aggregation pipeline to perform the conversion:

db.students.aggregate([
  { $project: { name: 1, age: { $convert: { input: "$age", to: "int" } } } }
])

The results are as follows:

{ "_id" : 1, "name" : "Tom", "age" : 22 }
{ "_id" : 2, "name" : "Jerry", "age" : 23 }
{ "_id" : 3, "name" : "Bob", "age" : 25 }
{ "_id" : 4, "name" : "Alice", "age" : 21 }

We can see that the age field has been successfully converted to a numeric type.

Conclusion

The $convert operator is a very useful aggregation pipeline operator in MongoDB that can be used to perform type conversions on data for easier processing and analysis.