

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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" }
- Related Questions & Answers
- How to query on list field in MongoDB?
- MongoDB query by sub-field?
- MongoDB query for a single field
- How to limit the amount of characters returned from a field in a MongoDB query?
- MongoDB query to update array with another field?
- Trim a string in Java to remove leading and trailing spaces
- Trim (Remove leading and trailing spaces) a string in C#
- MySQL query to get a field value that does not contain empty spaces?
- MongoDB query select and display only a specific field from the document?
- MongoDB query to change simple field into an object?
- Indexing large text field to make query faster in MongoDB
- How to add a field with static value to MongoDB find query?
- How to run MongoDB query to update only a specific field value?
- How to remove white spaces (leading and trailing) from string value in MongoDB?
- Field selection within MongoDB query using dot notation?
Advertisements