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

Đổi tên collection trong MongoDB (renameCollection)

Cú pháp

db.tenCollectionCu.renameCollection("tenCollectionMoi");

Ví dụ minh họa

1. Tạo collection và dữ liệu

> db.savingInformationDemo.insertOne({"StudentName":"Larry"});
> db.savingInformationDemo.insertOne({"StudentName":"John"});
> db.savingInformationDemo.insertOne({"StudentName":"Mike"});
> db.savingInformationDemo.insertOne({"StudentName":"Sam"});

2. Xem dữ liệu ban đầu

> db.savingInformationDemo.find().pretty();

3. Đổi tên collection

> db.savingInformationDemo.renameCollection("saveStudentInformation");
{ "ok" : 1 }

4. Kiểm tra collection mới

> db.saveStudentInformation.find();

Dữ liệu hiển thị bình thường với tên collection mới.

Lưu ý quan trọng

  • renameCollection không thể đổi tên collection giữa các database khác nhau (chỉ trong cùng database).
  • Nếu collection đích đã tồn tại, lệnh sẽ lỗi trừ khi dùng tùy chọn dropTarget: true.
  • Opertaion này khóa database trong quá trình thực hiện (blocking operation).
  • Không thể đổi tên collection hệ thống (system.*) hoặc view.