
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Leading and Trailing White Spaces from String in MongoDB
For this, you need to write some code using forEach(). Let us first create a collection with documents −
> db.removingWhiteSpaceDemo.insertOne({"Title":" Introduction to java "}); { "acknowledged" : true, "insertedId" : ObjectId("5cd66f387924bb85b3f4894c") }
Following is the query to display all documents from a collection with the help of find() method −
> db.removingWhiteSpaceDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd66f387924bb85b3f4894c"), "Title" : " Introduction to java " }
Following is the query to remove white spaces (leading and trailing) from string value −
> db.removingWhiteSpaceDemo.find({},{"Title": 1 }).forEach(function(myDocument) { myDocument.Title = myDocument.Title.trim(); db.removingWhiteSpaceDemo.update( { "_id": myDocument._id }, { "$set": { "Title": myDocument.Title } } ); });
Let us check the document once again from the above collection. Following is the query −
> db.removingWhiteSpaceDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cd66f387924bb85b3f4894c"), "Title" : "Introduction to java" }
Advertisements