Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách đổi tên trường (rename column) trong collection MongoDB

Giới thiệu

Để đổi tên trường (field/column) trong MongoDB, bạn sử dụng toán tử $rename trong update operation. Toán tử này đổi tên field mà không thay đổi giá trị.

Cú pháp

// Đổi tên cho TẤT CẢ document (multi: true)
db.collection.updateMany(
    {}, 
    { $rename: { "tenTruongCu": "tenTruongMoi" } }
);

// Đổi tên cho document thỏa điều kiện
db.collection.updateMany(
    { filter },
    { $rename: { "tenTruongCu": "tenTruongMoi" } }
);

Lưu ý: Cú pháp cũ update({}, {$rename:...}, false, true) đã deprecated. Dùng updateMany().

Ví dụ minh họa

1. Tạo collection

> db.doiTenTruong.insertOne({ "TenSinhVien": "Larry", "Tuoi": 23 });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ee2c6d628fa4220163b9a") }
> db.doiTenTruong.insertOne({ "TenSinhVien": "Sam", "Tuoi": 26 });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ee2d0d628fa4220163b9b") }
> db.doiTenTruong.insertOne({ "TenSinhVien": "Robert", "Tuoi": 27 });
{ "acknowledged" : true, "insertedId" : ObjectId("5c9ee2dbd628fa4220163b9c") }

2. Đổi tên trường "Tuoi" thành "TuoiSinhVien"

> db.doiTenTruong.updateMany(
    {}, 
    { $rename: { "Tuoi": "TuoiSinhVien" } }
);
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

3. Kết quả

> db.doiTenTruong.find().pretty();
{ "_id" : ObjectId("5c9ee2c6d628fa4220163b9a"), "TenSinhVien" : "Larry", "TuoiSinhVien" : 23 }
{ "_id" : ObjectId("5c9ee2d0d628fa4220163b9b"), "TenSinhVien" : "Sam", "TuoiSinhVien" : 26 }
{ "_id" : ObjectId("5c9ee2dbd628fa4220163b9c"), "TenSinhVien" : "Robert", "TuoiSinhVien" : 27 }

Đổi tên nhiều trường cùng lúc

db.collection.updateMany(
    {},
    { 
        $rename: { 
            "oldName1": "newName1",
            "oldName2": "newName2",
            "oldName3": "newName3"
        } 
    }
);

Đổi tên nested field

// Đổi "user.profile.fullName" thành "user.profile.name"
db.collection.updateMany(
    {},
    { $rename: { "user.profile.fullName": "user.profile.name" } }
);

Lưu ý quan trọng

  • $rename **không tạo field mới** nếu field cũ không tồn tại (bỏ qua silently)
  • Nếu field mới **đã tồn tại**, $rename sẽ **ghi đè (overwrite)** giá trị cũ!
  • Không thể rename _id field
  • Operation này **không thể rollback** - hãy backup trước
  • Trên collection lớn, operation có thể tốn thời gian và lock

Kiểm tra trước khi rename

// Kiểm tra field cũ tồn tại, field mới chưa tồn tại
db.collection.find({ 
    $and: [
        { "tenTruongCu": { $exists: true } },
        { "tenTruongMoi": { $exists: false } }
    ]
}).limit(1);

// Đếm số doc sẽ bị ảnh hưởng
db.collection.countDocuments({ "tenTruongCu": { $exists: true } });

Trong Aggregation (chỉ đổi tên trong kết quả, không sửa DB)

db.collection.aggregate([
    { $project: { 
        tenMoi: "$tenCu",
        tenCu: 0  // Ẩn field cũ
    } }
]);

Best Practice

  1. Backup database/collection trước khi rename
  2. Test trên staging environment
  3. Chạy trong maintenance window nếu collection lớn
  4. Cập nhật application code đồng thời (deploy cùng lúc)
  5. Monitor sau khi đổi: kiểm tra query, index, application logs