How to remove white spaces (leading and trailing) from string value 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" }

Updated on: 30-Jul-2019

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements