Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to trim spaces from field in MongoDB query?
To trim spaces from field in MongoDB, use the $trim operator within an aggregation pipeline. The $trim operator removes whitespace characters from the beginning and end of a string.
Syntax
db.collection.aggregate([
{ $project: {
fieldName: { $trim: { input: "$sourceField" } }
}}
])
Sample Data
db.demo217.insertMany([
{"FullName": " Chris Brown"},
{"FullName": " David Miller"},
{"FullName": " John Doe"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e3e5d1e03d395bdc213470f"),
ObjectId("5e3e5d2503d395bdc2134710"),
ObjectId("5e3e5d2b03d395bdc2134711")
]
}
Display all documents to see the original data with spaces ?
db.demo217.find();
{ "_id": ObjectId("5e3e5d1e03d395bdc213470f"), "FullName": " Chris Brown" }
{ "_id": ObjectId("5e3e5d2503d395bdc2134710"), "FullName": " David Miller" }
{ "_id": ObjectId("5e3e5d2b03d395bdc2134711"), "FullName": " John Doe" }
Example: Trim Spaces Using $trim
Use the $trim operator in aggregation to remove leading and trailing spaces ?
db.demo217.aggregate([
{ $project: { Name: { $trim: { input: "$FullName" } } } }
]);
{ "_id": ObjectId("5e3e5d1e03d395bdc213470f"), "Name": "Chris Brown" }
{ "_id": ObjectId("5e3e5d2503d395bdc2134710"), "Name": "David Miller" }
{ "_id": ObjectId("5e3e5d2b03d395bdc2134711"), "Name": "John Doe" }
Key Points
-
$trimonly works within aggregation pipelines, not in regular find queries. - The operator removes whitespace from both ends but preserves internal spaces.
- Use
$projectto create a new field with trimmed values.
Conclusion
The $trim operator effectively removes leading and trailing whitespace from string fields in MongoDB. Use it within aggregation pipelines with $project to clean up field values while preserving the original data structure.
Advertisements
