$convert
The $convert operator converts an expression into a value of the specified type.
Syntax
{
$convert: {
input: <expression>,
to: <type>,
format: <binData format>,
onError: <value to return on error>,
onNull: <value to return on null>
}
}
Parameters
input
objectrequiredThe input value to be converted to the specified type.
to
stringrequiredThe type to convert the input value into.
format
stringOptional. The binData format of the input or output when converting to/from binData.
onError
objectOptional. The value to return when conversion fails.
onNull
objectOptional. The value to return when input is null or missing.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop",
"staff": { "totalStaff": { "fullTime": 8 } }
}
Convert an Int to String
Convert the fullTime field from integer to string.
This query converts a numeric value to its string representation.
Query:
db.stores.aggregate([{
$match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
$project: {
fulltimeStaff: "$staff.totalStaff.fullTime",
fulltimeStaffAsString: {
$convert: {
input: "$staff.totalStaff.fullTime",
to: "string"
}
}
}
}])
Output:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"fulltimeStaff": 3,
"fulltimeStaffAsString": "3"
}
]
Convert an Int to Boolean
Convert the fullTime field to boolean (any positive value becomes true).
This query converts a numeric value to boolean type.
Query:
db.stores.aggregate([{
$match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
$project: {
fulltimeStaff: "$staff.totalStaff.fullTime",
fulltimeStaffAsBool: {
$convert: {
input: "$staff.totalStaff.fullTime",
to: "bool"
}
}
}
}])
Output:
[
{
"_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
"fulltimeStaff": 3,
"fulltimeStaffAsBool": true
}
]