Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Tuesday, 20 February 2024

LPAD in MongoDB

In MongoDB, there isn't a built-in LPAD function like in traditional SQL databases. However, you can achieve similar functionality using the aggregation framework and a combination of string manipulation operators. Here's how you can pad a string to the left in MongoDB:


Suppose you have a collection employees with documents containing an employee_name field, and you want to pad each employee_name to a length of 15 characters with asterisks (*) to the left:


db.employees.aggregate([

  {

    $addFields: {

      padded_name: {

        $concat: [

          {

            $substrCP: [

              "***************",

              0,

              { $subtract: [15, { $strLenCP: "$employee_name" }] }

            ]

          },

          "$employee_name"

        ]

      }

    }

  }

])


In this aggregation:


- $strLenCP calculates the length of the original employee_name.

- $subtract calculates the number of asterisks (*) needed to pad the string to a total length of 15 characters.

- $substrCP extracts a substring of asterisks (*) based on the calculated padding length.

- $concat concatenates the generated padding string with the original employee_name.


This aggregation will produce a new field padded_name in each document, containing the employee_name padded to a length of 15 characters with asterisks (*) to the left. Adjust the length and padding character as needed for your specific requirements.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.