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
   }
}


  1. input → The expression to evaluate and convert
  2. to → The target data type to which input should be converted. Supported types include double, string, objectId, bool, date, int, long, and decimal
  3. onError (optional) → The value to return if the conversion fails. If omitted, the default behavior is to raise an error
  4. onNull (optional) → The value to return if the input is null or missing. If omitted, the default behavior is to return null

Example




Picture showing the sample documents collection


db.Employees.aggregate([
   {
      $addFields: {
         newField: {
            $convert: {
               input: "$age",
               to: "date",
               onError:-1
               
            }
         }
      }
   }
])


Picture showing using the convert function for converting age to date


db.Employees.aggregate([
   {
      $addFields: {
         newField: {
            $convert: {
               input: "$age1",
               to: "date",
               onNull:3
            }
         }
      }
   }
])


Picture showing using the convert function for converting age to date



Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, June 5, 2024

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250