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

การลบคอลเลกชันทั้งหมดที่มีชื่อตรงกับสตริงใน MongoDB


หากต้องการลบคอลเลกชันทั้งหมดที่มีชื่อตรงกับสตริง คุณสามารถทำตามขั้นตอนบางอย่างได้ ใช้สำหรับวนซ้ำเพื่อวนซ้ำทุกคอลเลกชันและค้นหาชื่อคอลเลกชันนั้นด้วยสตริงที่แน่นอน หลังจากนั้น ใช้วิธีวางเพื่อลบคอลเลกชันทั้งหมด

สมมติว่าเรากำลังใช้ฐานข้อมูล "ตัวอย่าง" คอลเลกชันมีดังต่อไปนี้ในฐานข้อมูลตัวอย่าง

> show collections;

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteMultipleIdsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findMimimumElementInArrayDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
insertDocumentWithDateDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation

ตอนนี้ลบชื่อคอลเลกชันทั้งหมดที่ตรงกับสตริง "ลบ" ต่อไปนี้เป็นแบบสอบถาม

> var allCollectionName = db.getCollectionNames();
> for(var j= 0, colLength = allCollectionName.length; j< colLength ; j++){
...    var colName = allCollectionName[j];
...    if(colName.indexOf('delete') == 0){
...       db[colName].drop()
...    }
... }

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้

True

ตอนนี้ คุณจะเห็นว่าไม่มีคอลเล็กชันชื่อ "ลบ" เนื่องจากคอลเล็กชันทั้งหมดถูกลบออกจากฐานข้อมูลตัวอย่างเรียบร้อยแล้ว

ตอนนี้ให้เราตรวจสอบชื่อคอลเลกชันทั้งหมด ต่อไปนี้เป็นแบบสอบถาม

> show collections;

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้

arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findMimimumElementInArrayDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
insertDocumentWithDateDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation