MongoDB

Mongodb $ltrim $rtrim

As a developer, you may encounter issues due to mistakenly adding spaces somewhere in the code. Several types of whitespaces can appear in a string. Leading whitespaces refer to the spaces that appear at the beginning of a string, before any other characters. Trailing whitespaces refers to the spaces that appear at the end of a string, after other characters. The only difference between leading and trailing whitespaces is in the position where they appear in a string. Leading and trailing whitespaces can be removed using different operators, ltrim, and rtrim respectively in MongoDB and they have different purposes as well. Leading whitespaces can cause issues with data validation while trailing whitespaces can make it difficult to match strings in comparisons or searches.

Create Environment

Open the MongoDB command-line utility to get started with this guide. You need to add your connection string in the command-line utility to enter the environment and start using it. We will be starting with the first command “show dbs” which is used to display a list of all the databases that exists on the MongoDB server. The output of the command shows the names of the databases and the sizes of each database in bytes. In this case, there are four databases: “admin”, “config”, “local”, and “test”.

test> show dbs

admin 40.00 KiB

config 72.00 KiB

local 72.00 KiB

test 40.00 KiB

The second command “use test” is used here to switch the currently utilized database to the “test” database. The output of the command is “already on db test” which indicates that the current database is already set to “test”.

test> use test

already on db test

It is time to create a new collection within our database that is empty for now. To create a new collection called “Order” in a MongoDB database, we will be running the instruction shown below on the MongoDB shell. The function “db.createCollection” is used to create a new collection and the collection name “Order” is passed as an argument. The output of the command, “{ ok: 1 }”, indicates that the collection was successfully created.

test> db.createCollection("Order")

{ ok: 1 }

Now, we have executed the “show collections” command that is used to display a list of collections for the current database. In our case, the current database is “test” and the output is “Order” which indicates that there is a collection named “Order” in the “test” database.

test> show collections

Order

Insert Records to Collection

After adding a new collection to a database, we cannot just use it for implementation as it is empty for now i.e. “Order” collection. We need to insert records in the newly made collection. The command of MongoDB shown below will be utilized in the MongoDB shell that is inserting multiple documents into the “Order” collection in a MongoDB database “test”. The function “db.Order.insertMany” is used to insert multiple documents into a collection at once and an array of documents is passed as an argument. The output of the instruction shows that the documents were successfully inserted into the collection. The “insertedIds” field contains the unique identifier (_id) that was allocated to each record.

test> db.Order.insertMany([ {Title: "Soap", Desc: " Soap is very \n cheap in price. \n\n "},

... {Title: "Shampo", Desc: " Shampo is exp"}, {Title: "Facewash", Desc: "Very important"},

... {Title: "Toothpaste", Desc: "\nUsed\nDaily\n"}, {Title: "Detergent", Desc: null} ])

{

acknowledged: true,

insertedIds: {

'0': ObjectId("63c74f88ffaf487d61bdad32"),

'1': ObjectId("63c74f88ffaf487d61bdad33"),

'2': ObjectId("63c74f88ffaf487d61bdad34"),

'3': ObjectId("63c74f88ffaf487d61bdad35"),

'4': ObjectId("63c74f88ffaf487d61bdad36")

} }

Display Collection Records

After adding 5 documents to the collection “Order”, we will also cross-check the data to avoid any inconvenience at the time of implementing our examples. The command to query the “Order” collection in a MongoDB database contains the function “find({})” that is used to query a collection. The output is an array of the same 5 documents that we have added just now, each with an exceptional identifier (_id) that is allocated by MongoDB, a Title, and a Description.

test> db.Order.find({})

[

{_id: ObjectId("63c74f88ffaf487d61bdad32"), Title: 'Soap', Desc: ' Soap is very \n cheap in price. \n\n '},

{_id: ObjectId("63c74f88ffaf487d61bdad33"), Title: 'Shampo', Desc: ' Shampo is exp' },

{_id: ObjectId("63c74f88ffaf487d61bdad34"), Title: 'Facewash', Desc: 'Very important' },

{_id: ObjectId("63c74f88ffaf487d61bdad35"), Title: 'Toothpaste', Desc: '\nUsed\nDaily\n' },

{ _id: ObjectId("63c74f88ffaf487d61bdad36"), Title: 'Detergent', Desc: null }

]

Example 01: $ltrim Operator

As discussed earlier, $ltrim is an operator in MongoDB that is used to remove leading whitespace characters from a string field. This operator is going to be used in the update() method and it modifies the existing documents in the collection. In this example, we will be using the $ltrim operator in the MongoDB command to see its outputs. So, to query the “Order” collection in a MongoDB database and carry out an aggregation action on the documents in the collection, we have tried the listed below query in the MongoDB shell after successfully inserting the records into the collection.

The function “aggregate” is used to query a collection and perform a combination operation on the “Order” collection documents. The aggregation operation in this instruction utilizes the $project pipeline operator, which amends the records in the collection by including or eliminating certain fields. In this case, the $project operator includes the Title field and a new field called Desc which is obtained by applying the $ltrim operator to the Desc field of every document in the “Order” collection. Here, the $ltrim operator removes leading whitespaces (spaces at the start) from a string. The output array is the same as before but the leading whitespaces of the Desc fields have been removed.

test> db.Order.aggregate([ {$project: {Title: 1, Desc: { $ltrim: {input: "$Desc"} } } } ])

[

{ _id: ObjectId("63c74f88ffaf487d61bdad32"), Title: 'Soap', Desc: 'Soap is very \n cheap in price. \n\n ' },

{ _id: ObjectId("63c74f88ffaf487d61bdad33"), Title: 'Shampo', Desc: 'Shampo is exp' },

{ _id: ObjectId("63c74f88ffaf487d61bdad34"), Title: 'Facewash', Desc: 'Very important' },

{ _id: ObjectId("63c74f88ffaf487d61bdad35"), Title: 'Toothpaste', Desc: 'Used\nDaily\n' },

{ _id: ObjectId("63c74f88ffaf487d61bdad36"), Title: 'Detergent', Desc: null }

]

Example 02: $rtrim Operator

The “rtrim” operator does the exact opposite of the “ltrim” operator. The very same command has been utilized with a single word change i.e. “ltrim” is replaced by “rtrim” as shown below. The $project stage selects the “Title” field and creates a new field “Desc” which is the result of applying the $rtrim operator on the “Desc” field of the input documents or spaces at the end of all strings are removed.

test> db.Order.aggregate([ {$project: {Title: 1, Desc: { $rtrim: {input: "$Desc"} } } } ])

[

{_id: ObjectId("63c74f88ffaf487d61bdad32"), Title: 'Soap', Desc: ' Soap is very \n cheap in price.' },

{ _id: ObjectId("63c74f88ffaf487d61bdad33"), Title: 'Shampo', Desc: ' Shampo is exp' },

{ _id: ObjectId("63c74f88ffaf487d61bdad34"), Title: 'Facewash', Desc: 'Very important' },

{ _id: ObjectId("63c74f88ffaf487d61bdad35"), Title: 'Toothpaste', Desc: '\nUsed\nDaily' },

{ _id: ObjectId("63c74f88ffaf487d61bdad36"), Title: 'Detergent', Desc: null }

]

Conclusion

The article is about whitespaces and their types in the introductory paragraph. Along with that, we have provided a comparison of the ltrim and rtrim operators in MongoDB. By establishing a MongoDB environment, we have created a new collection and applied the ltrim and rtrim operators separately on one of its fields within two separate examples to elaborate on the use of both operators. In the end, we got the result with no leading and trailing whitespaces in the particular string field.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.