Toán tử $trim (MongoDB 4.0+) loại bỏ khoảng trắng đầu/cuối chuỗi trong aggregate pipeline.
Dữ liệu mẫu có khoảng trắng đầu
> db.demo217.insertOne({"FullName":" Chris Brown"});
> db.demo217.insertOne({"FullName":" David Miller"});
> db.demo217.insertOne({"FullName":" John Doe"});
Pipeline aggregate $trim
> db.demo217.aggregate([
{ $project: { Name: { $trim: { input: "$FullName" } } } }
]);
Kết quả
{ "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "Name" : "David Miller" }
{ "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "Name" : "John Doe" }
Cú pháp đầy đủ:
{ $trim: { input: , chars: } }
input: Chuỗi cần trim (bắt buộc)chars: Các ký tự cần xóa (tùy chọn, mặc định khoảng trắng, tab, newline)
Ví dụ tùy chỉnh:
{ $trim: { input: "$FullName", chars: " .,-_" } } // Xóa space, dot, comma, dash, underscore
Toán tử liên quan:
$ltrim: Chỉ xóa đầu$rtrim: Chỉ xóa cuối- Trong update (MongoDB 4.2+):
db.coll.updateMany({}, [{$set: {Name: {$trim: "$FullName"}}} ])