Để đổi tên collection trong MongoDB, bạn sử dụng phương thức renameCollection().
Cú pháp
db.oldCollectionName.renameCollection('newCollectionName');
Ví dụ minh họa
1. Xem danh sách collection hiện có
> use sample switched to db sample > show collections;
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo employee informationAboutDelete internalArraySizeDemo prettyDemo selectWhereInDemo sourceCollection updateInformation userInformation
2. Đổi tên collection
Đổi informationAboutDelete thành deleteSomeInformation:
> db.informationAboutDelete.renameCollection('deleteSomeInformation');
{ "ok" : 1 }
3. Kiểm tra kết quả
> show collections;
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteSomeInformation employee internalArraySizeDemo prettyDemo selectWhereInDemo sourceCollection updateInformation userInformation
Collection informationAboutDelete đã biến mất, thay vào đó là deleteSomeInformation.
Đặc điểm của renameCollection
- Atomic: Thao tác nguyên tử, không làm mất dữ liệu
- Nhanh: Chỉ đổi metadata, không copy dữ liệu
- Giữ nguyên indexes: Tất cả indexes được chuyển sang collection mới
- Không thể rename cross-database: Chỉ đổi tên trong cùng database
Đổi tên cross-database (khác database)
MongoDB không hỗ trợ rename trực tiếp sang database khác. Cách làm:
// Cách 1: Aggregation $out (MongoDB 4.2+)
db.sourceColl.aggregate([{$match:{}}, {$out: "targetDB.newCollName"}]);
// Cách 2: mongoexport/mongoimport
mongoexport -d sourcedb -c sourceColl -o data.json
mongoimport -d targetdb -c newCollName --file data.json
// Sau đó drop collection cũ
db.sourceColl.drop()
Lưu ý
- Tên collection mới không được trùng với collection đã tồn tại
- Không thể rename collection hệ thống (system.*)
- Sau khi rename, các application cần cập nhật tên collection mới