MongoDB 4.0+ มี operator $trim สำหรับตัด whitespace (space, tab, newline) ออกจากต้นและท้าย string ใช้ใน aggregate pipeline
สร้างคอลเลกชันและข้อมูลตัวอย่าง (มีช่องว่างหน้า)
> 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") }
แสดงข้อมูลก่อน Trim
> db.demo217.find();
ผลลัพธ์: FullName มี 2 spaces นำหน้า (" Chris Brown")
Query Trim Spaces ด้วย $trim
> db.demo217.aggregate([
{ $project: { Name: { $trim: { input: "$FullName" } } } }
])
คำอธิบาย:
$trim: {input: "$FullName"}: ตัด whitespace ทั้งหน้าและหลัง (default chars: space, tab, newline)- สร้าง field ใหม่ Name ที่ trimmed แล้ว
ผลลัพธ์
{ "_id" : ObjectId("5e3e5d1e03d395bdc213470f"), "Name" : "Chris Brown" }
{ "_id" : ObjectId("5e3e5d2503d395bdc2134710"), "Name" : "David Miller" }
{ "_id" : ObjectId("5e3e5d2b03d395bdc2134711"), "Name" : "John Doe" }
$trim Options แบบเต็ม
{ $trim: { input: , chars: } }
input: string ที่จะ trim (required)chars: characters ที่จะตัด (optional, default = whitespace)
ตัวอย่าง Custom Chars
// ตัดเฉพาะตัวอักษร x, y, z จากหน้าและหลัง
{ $trim: { input: "$str", chars: "xyz" } }
// ตัดเฉพาะหน้า ($ltrim) หรือหลัง ($rtrim) - MongoDB 4.0+
{ $ltrim: { input: "$FullName" } } // ตัดหน้าเท่านั้น
{ $rtrim: { input: "$FullName" } } // ตัดหลังเท่านั้น
Update Documents แบบ Permanent (MongoDB 4.2+)
ใช้ update with aggregation pipeline เพื่อ update จริงใน collection:
db.demo217.updateMany(
{},
[{ $set: { FullName: { $trim: { input: "$FullName" } } }}]
)
ใช้ใน $match (Filter ด้วย Trimmed Value)
db.demo217.aggregate([
{ $match: {
$expr: { $eq: [{ $trim: { input: "$FullName" } }, "Chris Brown"] }
}}
])
String Operators อื่นๆ ที่เกี่ยวข้อง
| Operator | คำอธิบาย |
|---|---|
$trim | ตัดหน้าและหลัง |
$ltrim | ตัดหน้าเท่านั้น |
$rtrim | ตัดหลังเท่านั้น |
$split | แยก string ด้วย delimiter |
$substr / $substrBytes / $substrCP | ตัด substring (byte/codepoint) |
$toLower / $toUpper | เปลี่ยน case |
$replaceOne / $replaceAll | แทนที่ substring (MongoDB 4.4+) |