MongoDB – Add Padding logic prefix or postfix

Adding Leading zero to mongo field

Today this article will see how to write a query MongoDB – Add Padding logic with prefix or suffix examples. You can address various requirements like adding or prefixing existing field values in MongoDB data.

Today in this article, we will cover below aspects,

We shall see examples for MongoDB field query where we will update the records based on field length value greater than or less than of specified value. We will update the records using mongo-shell query.

We already looked at a simple way of adding or updating a new field to the document in our previous MongoDB sample series.

We shall also see how to create a similar query using another language like C# Mongo driver.

Getting started

Here below is a sample schema or document we shall use for field length query and will cover less than or greater than length query for field value “ZIP”.

Mongo Padding field elements with postfix/trailing string

Here we will be using the below schema where the Zip code field is currently only 5 digits. We will postfix the zipcode with an additional zero as below using Mongo aggregation query.

Update ZipCode as 10 Character field by adding a trailing string

Source example

{
  "_id": {
    "$oid": "61ec0d5e9e5a92743c245376"
  },
  "Name": "JK",
  "City": "1",
  "Country": "USA",
  "States": "NY",
  "Zip": "67889"
}

Below is how we are expecting the Zip code by adding trailing zeros.

{
  "Zip": "67889-0000"
}

Pattern:

db.employee.updateMany({},

  [{
    $set: {
      "Zip": {
        $toString: {
          $concat: [{
            $toString: "$Zip"
          }, {
            $substrCP: ["-0000", 0, {
              $subtract: [10, {
                $strLenCP: {
                  $toString: "$Zip"
                }
              }]
            }]
          }]
        }
      }
    }
  }]

)

Here is the output of the query,

Mongodb add leading zero mongo shell query

Mongo Padding field elements with prefix/leading string

Let’s look at the below sample JSON where we try to add leading zeros as prefixes to the existing “UserId”.

Update userId as 10 Character field by adding the leading zero

I have UserId ranging from 0 to 10 digits but to keep uniformity, let’s say we want to add a leading zero for all such Ids.

Example:

“999” -> “0000000999”

OR

“99999” -> “000009999”

Query Pattern

db.category.updateOne({}, [{
  $set: {
    "UserId": {
      $toString: {
        $concat: [{
          $substrCP: ["0000000000", 0, {
            $subtract: [10, {
              $strLenCP: {
                $toString: "$UserId"
              }
            }]
          }]
        }, {
          $toString: "$UserId"
        }]
      }
    }
  }
}], {
  multi: true
})

Above the same query can be executed using updateMany() function to achieve the same result as below,

MongoDB Add Padding logic with prefix or suffix

Here is the output of the query,

blank

Kindly visit the below article for all examples using the C# MongoDB driver,

The above query can be extended for filters or conditional updates as required.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.




2 thoughts on “MongoDB – Add Padding logic with prefix or suffix examples

Leave a Reply

Your email address will not be published. Required fields are marked *