본문 바로가기
프로그래밍

[mongoDB] mongo shell을 이용해서 collection 여러개 삭제하기

by choihyuunmin 2024. 4. 24.
728x90

mongo DB에 TTL을 등록하지 않고 며칠 크롤러를 돌리다 보니 collection이 여러개 쌓였습니다.

제가 사용하고 있는 Robo 3T가 옛날 버전이라 collection을 다중선택해서 삭제하는 기능이 없어

mongo shell을 작성해서 삭제를 해보겠습니다.

1. Mongo Shell

// 오늘의 날짜를 가져오는 함수
function getTodayDate() {
    var today = new Date();
    var year = today.getFullYear();
    var month = String(today.getMonth() + 1).padStart(2, '0');
    var day = String(today.getDate()).padStart(2, '0');
    return year + month + day;
}

제가 수집하는 데이터의 형식은 특정 시스템 뒤에 언더바(_)와 날짜가 붙는 형식입니다.

오늘 날짜가 붙어있는 것을 제외한 collection을 삭제하기 위해 날짜를 구해줍니다.

mongo shell은 javascript 기반이기 때문에 Date 클래스를 가져와서 today에 할당해줍니다.

Date의 형식은 아래와 같습니다.

var today = new Date();
>> ISODate("2024-04-24T01:06:24.643Z")

Date를 통해 만든 today 인스턴스의 getMonth와 getDate 함수는 한자리 일때 앞에 0을 제거해서 반환해주기 때문에 앞에 0을 붙여주는 작업을 해줍니다.

// 오늘의 날짜를 제외한 컬렉션을 삭제하는 함수
function deleteOldCollections() {
    var todayDate = getTodayDate();
    var collectionNames = db.getCollectionNames();

    collectionNames.forEach(function(collectionName) {
        if (collectionName.match(/^gyeongnam_\d+$/) && !collectionName.endsWith(todayDate)) {
            db[collectionName].drop();
            print("Collection " + collectionName + " deleted.");
        }
    });
}

getTodayDate 함수를 통해 오늘 날짜를 붙여서, forEach를 돌면서 하나씩 삭제해줍니다.

collectionName.match(/^gyeongnam_\d+$/) && !collectionName.endsWith(todayDate)

gyeonnam으로 시작하고 뒤에 날짜가 붙는 regex를 찾아서 삭제하도록 합니다.

2. 전체 코드

// 오늘의 날짜를 가져오는 함수
function getTodayDate() {
    var today = new Date();
    var year = today.getFullYear();
    var month = String(today.getMonth() + 1).padStart(2, '0');
    var day = String(today.getDate()).padStart(2, '0');
    return year + month + day;
}

// 오늘의 날짜를 제외한 컬렉션을 삭제하는 함수
function deleteOldCollections() {
    var todayDate = getTodayDate();
    var collectionNames = db.getCollectionNames();

    collectionNames.forEach(function(collectionName) {
        if (collectionName.match(/^gyeongnam_\d+$/) && !collectionName.endsWith(todayDate)) {
            db[collectionName].drop();
            print("Collection " + collectionName + " deleted.");
        }
    });
}

// 함수 실행
deleteOldCollections();