Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

วิธีเปลี่ยนชื่อ Collection ใน MongoDB ด้วย renameCollection()

ใช้เมธอด renameCollection() บน Collection Object เพื่อเปลี่ยนชื่อ Collection ได้โดยตรง

รูปแบบคำสั่ง

db.oldCollectionName.renameCollection("newCollectionName");

ตัวอย่างเต็มรูปแบบ

1. สร้าง Collection และข้อมูลตัวอย่าง

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

2. แสดงข้อมูลก่อนเปลี่ยนชื่อ

> db.savingInformationDemo.find().pretty();
{ "_id" : ObjectId("..."), "StudentName" : "Larry" }
{ "_id" : ..., "StudentName" : "John" }
{ "_id" : ..., "StudentName" : "Mike" }
{ "_id" : ..., "StudentName" : "Sam" }

3. เปลี่ยนชื่อ Collection

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

4. ตรวจสอบ: Collection เก่าหาย, Collection ใหม่มีข้อมูล

> db.saveStudentInformation.find();
{ "_id" : ObjectId("..."), "StudentName" : "Larry" }
{ "_id" : ..., "StudentName" : "John" }
{ "_id" : ..., "StudentName" : "Mike" }
{ "_id" : ..., "StudentName" : "Sam" }

ตัวเลือกเพิ่มเติม

// dropTarget: true = ทับ Collection ใหม่ถ้ามีอยู่แล้ว
db.oldColl.renameCollection("newColl", { dropTarget: true });

ข้อจำกัดและข้อควรระวัง

  • ไม่สามารถ Rename ข้าม Database (ต้องอยู่ใน DB เดียวกัน)
  • ต้องการสิทธิ์ renameCollection บน Database
  • Operation นี้ Blocking (Lock Database ระหว่างดำเนินการ)
  • Indexes จะถูกย้ายไปพร้อม Collection
  • Views ที่ reference Collection นี้จะ Broken (ต้อง Recreate)

วิธีอื่น: Copy + Drop (Cross Database)

// ถ้าต้องย้ายข้าม DB
db.oldColl.aggregate([ { $match: {} }, { $out: "newDB.newColl" } ]);
db.oldColl.drop();

สรุป

  • ใช้ db.oldName.renameCollection("newName") สำหรับ Rename ใน DB เดียวกัน
  • คืนค่า { "ok": 1 } ถ้าสำเร็จ
  • ข้อมูลและ Indexes ย้ายไปพร้อมกัน
  • Cross-DB ต้องใช้ $out + drop แทน