刪除所有與 MongoDB 中的字串匹配的名稱的集合


要刪除所有名稱與字串匹配的集合,可以遵照一些步驟進行。使用 for 迴圈迭代檢視所有集合,然後找到包含特定字串的特定集合名稱。此後,使用 drop 方法來刪除所有集合。

我們現在使用資料庫“sample”。示例資料庫中的集合如下

> 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

現在刪除所有名稱與字串“delete”匹配的集合。查詢如下

> 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

現在可以看到沒有名稱為“delete”的集合,因為所有集合已成功從示例資料庫中刪除。

現在讓我們檢視所有集合名稱。查詢如下

> 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

更新於: 30-7-2019

480 次檢視

開啟你的 事業

完成課程並取得認證

立即開始
廣告
© . All rights reserved.