$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

inputobjectrequired

The input value to be converted to the specified type.

tostringrequired

The type to convert the input value into.

formatstring

Optional. The binData format of the input or output when converting to/from binData.

onErrorobject

Optional. The value to return when conversion fails.

onNullobject

Optional. 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
  }
]

Related