Giới thiệu
Để nối chuỗi (concatenate) từ hai trường thành một trường mới, MongoDB cung cấp toán tử $concat trong aggregation pipeline.
Cú pháp
db.tenCollection.aggregate([
{ $project: {
"tenTruongMoi": {
$concat: [ "$truong1", " kyTuPhanCach ", "$truong2" ]
}
} }
]);
Ví dụ minh họa: Nối họ và tên
1. Tạo collection
> db.noiChuoiDemo.insertOne({"Ho":"John","Ten":"Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9bb7362d66697741252444") }
> db.noiChuoiDemo.insertOne({"Ho":"John","Ten":"Smith"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9bb7402d66697741252445") }
> db.noiChuoiDemo.insertOne({"Ho":"Carol","Ten":"Taylor"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9bb74c2d66697741252446") }
> db.noiChuoiDemo.insertOne({"Ho":"David","Ten":"Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9bb7752d66697741252447") }
> db.noiChuoiDemo.insertOne({"Ho":"James","Ten":"Williams"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9bb7862d66697741252448") }
2. Nối thành Họ Tên đầy đủ
> db.noiChuoiDemo.aggregate([
{ $project: {
"HoTenDayDu": {
$concat: [ "$Ho", " / ", "$Ten" ]
}
} }
]);
3. Kết quả
{ "_id" : ObjectId("..."), "HoTenDayDu" : "John / Doe" }
{ "_id" : ObjectId("..."), "HoTenDayDu" : "John / Smith" }
{ "_id" : ObjectId("..."), "HoTenDayDu" : "Carol / Taylor" }
{ "_id" : ObjectId("..."), "HoTenDayDu" : "David / Miller" }
{ "_id" : ObjectId("..."), "HoTenDayDu" : "James / Williams" }
Mở rộng: Các toán tử chuỗi hữu ích khác
| Toán tử | Mô tả | Ví dụ |
|---|---|---|
$substr | Cắt chuỗi con | { $substr: ["$tenTruong", 0, 5] } |
$toLower | Chuyển thành chữ thường | { $toLower: "$tenTruong" } |
$toUpper | Chuyển thành chữ HOA | { $toUpper: "$tenTruong" } |
$trim | Xóa khoảng trắng đầu/cuối | { $trim: { input: "$tenTruong" } } |
Lưu ý
$concatchỉ hoạt động với kiểu string. Nếu trường có thể null, hãy dùng$ifNullđể xử lý- Ví dụ an toàn:
{ $concat: [ { $ifNull: ["$Ho", ""] }, " ", { $ifNull: ["$Ten", ""] } ] }