Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to remove white spaces (leading and trailing) from string value in MongoDB?
To remove white spaces (leading and trailing) from string values in MongoDB, you can use the forEach() method combined with JavaScript's trim() function to iterate through documents and update them.
Syntax
db.collection.find().forEach(function(doc) {
doc.fieldName = doc.fieldName.trim();
db.collection.update(
{ "_id": doc._id },
{ "$set": { "fieldName": doc.fieldName } }
);
});
Sample Data
Let us first create a collection with documents containing white spaces ?
db.removingWhiteSpaceDemo.insertOne({
"Title": " Introduction to java "
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd66f387924bb85b3f4894c")
}
Display the document to see the white spaces ?
db.removingWhiteSpaceDemo.find();
{ "_id": ObjectId("5cd66f387924bb85b3f4894c"), "Title": " Introduction to java " }
Remove White Spaces
Use forEach() with trim() to remove leading and trailing white spaces ?
db.removingWhiteSpaceDemo.find({}, {"Title": 1}).forEach(function(myDocument) {
myDocument.Title = myDocument.Title.trim();
db.removingWhiteSpaceDemo.update(
{ "_id": myDocument._id },
{ "$set": { "Title": myDocument.Title } }
);
});
Verify Result
Check the document to confirm white spaces are removed ?
db.removingWhiteSpaceDemo.find();
{ "_id": ObjectId("5cd66f387924bb85b3f4894c"), "Title": "Introduction to java" }
Conclusion
Use forEach() with JavaScript's trim() method to remove leading and trailing white spaces from string fields. This approach iterates through documents and updates each one individually using the $set operator.
Advertisements
