How to clone MongoDB collection indexes from one server to another

from pymongo import MongoClient


def clean_indexes(indexes):
    """Remove index for id and clean ns attribute."""
    for index in indexes:
        if index['name'] == '_id_':
            continue
        index.pop('ns', None)
        yield index


def get_indexes(db):
    """Get map collection name -> list of cleaned indexes."""
    coll_indexes_map = {}
    for coll in db_source.list_collections():
        coll_name = coll['name']
        coll_indexes_map[coll_name] = list(clean_indexes(list(db[coll_name].list_indexes())))
    return coll_indexes_map


def create_indexes(db, coll_indexes_map):
    for coll_name, indexes in coll_indexes_map.items():
        if indexes:
            db.command('createIndexes', coll_name, indexes=indexes)


def clone_indexes(source_uri, dest_uri):
    source_db = MongoClient(source_uri).get_database()
    dest_db = MongoClient(dest_uri).get_database()

    coll_indexes_map = get_indexes(source_db)
    create_indexes(dest_db, coll_indexes_map)


clone_indexes(
    source_uri='mongodb+srv://user:password@host1/db',
    dest_uri='mongodb+srv://user:password@host2/db'
)
comments powered by Disqus