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 for evaluation and conversion.
- to → Specifies the target data type for the conversion. Supported types include: double, string, objectId, bool, date, int, long, and decimal.
- onError (optional) → The value returned if the conversion fails. If omitted, the default behavior is to raise an error.
- onNull (optional) → The value returned when the input is null or missing. If omitted, the default action 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
}
}
}
}
])
Posted By - | Karan Gupta |
|
Posted On - | Wednesday, June 5, 2024 |