Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 특정 문자열과 일치하는 컬렉션 전체 삭제하는 방법

MongoDB에서 특정 문자열과 일치하는 컬렉션 일괄 삭제하기

MongoDB에서 이름이 특정 문자열과 일치하는 컬렉션을 여러 개 한 번에 삭제해야 할 때가 있습니다. 이럴 때는 for 루프로 데이터베이스의 모든 컬렉션을 순회하면서 조건에 맞는 컬렉션 이름을 찾은 뒤, drop() 메서드를 호출하면 됩니다.

아래 예시에서는 "sample"이라는 데이터베이스를 사용합니다.

1단계: 현재 컬렉션 목록 확인

먼저 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

2단계: for 루프와 drop()으로 일치하는 컬렉션 삭제

이제 이름이 "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가 출력됩니다.

true

여기서 indexOf('delete') == 0 조건은 컬렉션 이름이 "delete"로 시작하는 경우를 의미합니다. 만약 이름 중간에 문자열이 포함된 컬렉션까지 모두 찾고 싶다면 조건을 colName.indexOf('delete') !== -1로 변경하면 됩니다.

3단계: 삭제 결과 확인

이제 sample 데이터베이스에는 이름이 "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

출력 결과를 보면 deleteAllRecordsDemo, deleteDocuments, deleteDocumentsDemo, deleteMultipleIdsDemo, deleteSomeInformation 등 "delete"로 시작했던 컬렉션들이 모두 사라진 것을 확인할 수 있습니다.

마무리

이처럼 db.getCollectionNames()로 컬렉션 이름 배열을 가져온 뒤 반복문으로 조건을 검사하고 drop()을 호출하면, 특정 패턴에 맞는 컬렉션을 손쉽게 일괄 삭제할 수 있습니다. 단, drop()은 되돌릴 수 없으므로 운영 환경에서는 삭제 대상 컬렉션을 먼저 충분히 검증한 후 실행하는 것이 안전합니다.