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

วิธีลบคอลเลกชัน MongoDB ที่ชื่อ 'group' (คำสงวน)

group เป็นชื่อเมธอดใน MongoDB ไม่ควรใช้เป็นชื่อคอลเลกชัน แต่หากสร้างไว้แล้ว สามารถลบได้ด้วย getCollection('group').drop()

ตัวอย่างการสร้างและลบคอลเลกชันชื่อ group

สร้างคอลเลกชันและเพิ่มข้อมูล:

> db.createCollection('group');
{ "ok" : 1 }
> db.getCollection('group').insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80fe9623186894665ae3c") }
> db.getCollection('group').insertOne({"StudentName":"Robert"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cb80fef623186894665ae3d") }

แสดงข้อมูล:

> db.getCollection('group').find().pretty();

ผลลัพธ์:

{ "_id" : ObjectId("5cb80fe9623186894665ae3c"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cb80fef623186894665ae3d"), "StudentName" : "Robert" }

ลบคอลเลกชันชื่อ 'group'

> db.getCollection('group').drop();

ผลลัพธ์:

True

สรุป: สำหรับชื่อคอลเลกชันที่เป็นคำสงวน (Reserved Keywords) หรือมีอักขระพิเศษ ให้ใช้ db.getCollection('collectionName') เพื่อเข้าถึงก่อน แล้วค่อยเรียก .drop()