How to trim spaces from field in MongoDB query?

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 30-Mar-2020 12:39:45
Advertisements