How to trim spaces from field in MongoDB query?


To trim spaces from field, use $trim in MongoDB. Let us create a collection with documents −

> db.demo217.insertOne({"FullName":"   Chris Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e5d1e03d395bdc213470f")
}
> db.demo217.insertOne({"FullName":"   David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e5d2503d395bdc2134710")
}
> db.demo217.insertOne({"FullName":"   John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3e5d2b03d395bdc2134711")
}

Display all documents from a collection with the help of find() method −

> db.demo217.find();

This will produce the following output −

{ "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "FullName" : "   Chris Brown" }
{ "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "FullName" : "   David Miller" }
{ "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "FullName" : "   John Doe" }

Following is the query to trim spaces from field in MongoDB −

> db.demo217.aggregate([
...    { $project: { Name: { $trim: { input: "$FullName" } } } }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "Name" : "David Miller" }
{ "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "Name" : "John Doe" }

Updated on: 30-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements