Articles → MONGODB → $Convert Aggregation Function In Mongodb
$Convert Aggregation Function In Mongodb
Purpose
Syntax
{
$convert: {
input: <expression>,
to: <type>,
onError: <expression>, // Optional
onNull: <expression> // Optional
}
}
- input → The expression to evaluate and convert
- to → The target data type to which input should be converted. Supported types include double, string, objectId, bool, date, int, long, and decimal
- onError (optional) → The value to return if the conversion fails. If omitted, the default behavior is to raise an error
- onNull (optional) → The value to return if the input is null or missing. If omitted, the default behavior is to return null
Example
db.Employees.aggregate([
{
$addFields: {
newField: {
$convert: {
input: "$age",
to: "date",
onError:-1
}
}
}
}
])
db.Employees.aggregate([
{
$addFields: {
newField: {
$convert: {
input: "$age1",
to: "date",
onNull:3
}
}
}
}
])