
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
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" }
Advertisements