MongoDB 컬렉션 간 인덱스를 복사하는 Python 예제

Jiyeon's TechNote·2025년 5월 19일
1

MongoDB의 한 데이터베이스에서 다른 데이터베이스로, 컬렉션별로 인덱스를 복사합니다.
단, 기본 인덱스인 _id_ 는 제외하고 복사함.

함수 정의: copy_indexes(...)

파라미터명설명
source_uri소스 MongoDB 인스턴스 URI
source_db_name소스 데이터베이스 이름
target_uri타겟 MongoDB 인스턴스 URI
target_db_name타겟 데이터베이스 이름

from pymongo import MongoClient

def copy_indexes(source_uri, source_db_name, target_uri, target_db_name):
    # 소스와 타겟 MongoDB 연결
    source_client = MongoClient(source_uri)
    source_db = source_client[source_db_name]

    target_client = MongoClient(target_uri)
    target_db = target_client[target_db_name]

    # 소스 DB의 모든 컬렉션 이름 가져오기
    collection_names = source_db.list_collection_names()

    for collection_name in collection_names:
        print(f"📁 복사 중: {collection_name}")

        source_collection = source_db[collection_name]
        target_collection = target_db[collection_name]  # 컬렉션이 없으면 pymongo가 자동 생성함

        # 인덱스 리스트 (기본 _id 인덱스는 제외)
        indexes = [idx for idx in source_collection.list_indexes() if idx['name'] != '_id_']

        # 인덱스 복사
        for index in indexes:
            # 인덱스 키를 리스트의 튜플로 변환하되, 방향 값을 명시적으로 int로 변환
            keys = [(k, int(v)) for k, v in index['key'].items()]
            kwargs = {k: v for k, v in index.items() if k not in ['key', 'ns', 'v']}
            target_collection.create_index(keys, **kwargs)

        print(f"✅ 완료: {collection_name} 인덱스 복사")

    print("🎉 모든 컬렉션 인덱스 복사 완료")


# 예시 실행
copy_indexes(
    source_uri="mongodb://user:password@mongodb-1.internal:27017",
    source_db_name="AAADB",
    target_uri="mongodb://user:password@mongodb-2.internal:27017",
    target_db_name="BBBDB"

해당 스크립트를 실행하면 AAADB의 인덱스들을 BBBDB로 복사합니다.

##주의 사항##

  1. 대상 컬렉션에 이미 같은 인덱스가 있을 경우 중복 생성은 되지 않지만, name 충돌 등의 이슈가 발생할 수 있음

  2. 데이터 자체는 복사되지 않음 (인덱스만 복사)

  3. 인덱스의 unique/sparse 조건도 그대로 복사되므로, 타겟 컬렉션이 비어있지 않다면 충돌 가능성 존재

profile
바쁘다 바빠 현대사회 엔지니어🙋‍♀️

0개의 댓글