Tüm Ürünler
Search
Belge Merkezi

ApsaraDB for MongoDB:Restore a cloud disk backup to a self-managed database

Son Güncelleme:Oct 03, 2026

Bu konu, ApsaraDB for MongoDB örneğinin bulut disk yedek dosyasından verilerin mongorestore kullanılarak kendi kendine yönetilen bir MongoDB veritabanına nasıl geri yükleneceğini açıklar.

Arka plan bilgileri

MongoDB, resmi yedekleme ve geri yükleme araçları olan Mongodump ve Mongorestore sunar. ApsaraDB for MongoDB, mantıksal yedekler oluşturmak için Mongodump kullanır; bu yedekleri daha sonra Mongorestore kullanarak kendi kendine yönetilen bir MongoDB veritabanına geri yükleyebilirsiniz.

Kullanım notları

  • MongoDB veritabanınızla uyumlu bir mongorestore sürümü kullanın. Sık güncellemeler nedeniyle eski mongorestore sürümleri yeni veritabanı sürümleriyle uyumsuz olabilir. Daha fazla bilgi için bkz. mongorestore.

  • Bir koleksiyon çok az veri içerse ve yalnızca tek bir BSON dosyasına sahip olsa bile (örneğin myDatabase/myCollection/data/myCollection_0_part0.bson), BSON dosyalarını birleştirmeniz veya yeniden adlandırmanız gerekir. Bunun nedeni mongorestore aracının BSON dosyalarını dosya adı ön eklerine göre işlemesidir.

  • Bulut disk yedeğini indirirken, indirme işlemi şemaları korunan boş koleksiyonları da işler ve veritabanı ile koleksiyon adı bilgilerini içeren boş bir BSON dosyası oluşturur. mongorestore aracı bu boş dosyaları doğru şekilde işleyebilir.

  • Parçalı bir küme örneği için indirilen bulut disk yedek dosyası artık parçalama rota bilgilerini içermez. Bu nedenle yedek verileri tek düğümlü, çoğaltma kümesi veya parçalı küme örneklerinden herhangi birine geri yükleyebilirsiniz. Verileri parçalı bir küme örneğine geri yüklemek istiyorsanız ön parçalama yapmanız gerekir.

Ön koşullar

  • Kendi kendine yönetilen MongoDB veritabanınızı barındıran istemcide (yerel sunucu veya ECS örneği), ApsaraDB for MongoDB örneğinizin sürümüyle eşleşen bir MongoDB sürümü yükleyin. Kurulum talimatları için bkz. MongoDB'yi Yükleyin.

  • Mantıksal yedek dosyasını indirdiniz. İndirmediyseniz bkz. Yedekleme dosyalarını indirin.

Yordam

  1. İndirilen yedek dosyasını hem mongorestore aracını hem de kendi kendine yönetilen MongoDB veritabanınızı barındıran istemciye kopyalayın.

  2. Yedek dosyasının sıkıştırmasını açın.

    Yedek dosyalarını sırasıyla zstd ve gzip sıkıştırma algoritmalarını kullanan tar.zst veya tar.gz biçiminde indirebilirsiniz. CreateDownload OpenAPI işleminin UseZstd parametresini kullanarak indirme biçimini seçebilirsiniz.

    tar.zst (Konsol)

    zstd -d -c <backup_file.tar.zst> | tar -xvf - -C <extraction_directory>

    zstd aracının istemcide yüklü olduğundan ve çıkarma dizininin var olduğundan emin olun.

    Örnek:

    mkdir -p ./download_test/test1
    zstd -d -c test1.tar.zst | tar -xvf - -C /Users/xxx/Desktop/download_test/test1/

    tar.gz (API)

    tar -zxvf <backup_file.tar.gz> -C <extraction_directory>

    Çıkarma dizininin var olduğundan emin olun.

    Örnek:

    mkdir -p ./download_test/test1
    tar -zxvf testDB.tar.gz -C /Users/xxx/Desktop/download_test/test1/
  3. BSON dosyalarını birleştirin.

    Python ortamına sahip bir istemcide aşağıdaki betiği kopyalayın ve merge_bson_files.py olarak kaydedin.

    import os
    import struct
    import sys
    import argparse
    import shutil
    import re
    
    # Handle strings for compatibility with both Python 2 and 3
    if sys.version_info[0] >= 3:
        unicode = str
    
    def merge_single_bson_dir(input_dir: str, output_dir: str, namespace: str) -> None:
        """
        Merges BSON files within a single directory.
    
        Args:
            input_dir (str): The directory path containing the BSON files.
            output_dir (str): The directory path for the output file.
            namespace (str): The name of the output file (without extension).
        """
        try:
            # Get all BSON files matching the ***_*_part*.bson pattern and sort them by name
            files = [f for f in os.listdir(input_dir) if re.match(r'^.+_.+_part\d+\.bson$', f)]
            files.sort()  # Sort by filename
    
            if not files:
                print("No matching .bson files found in {}".format(input_dir))
                return
    
            output_file = os.path.join(output_dir, "{}.bson".format(namespace))
            if os.path.exists(output_file):
                print("Output file {} already exists, skipping...".format(output_file))
                return
    
            print("Merging {} files into {}...".format(len(files), output_file))
    
            # Stream-read and merge the files
            total_files = len(files)
            with open(output_file, "wb") as out_f:
                for index, filename in enumerate(files, 1):
                    file_path = os.path.join(input_dir, filename)
                    print("  Processing file {}/{}: {}...".format(index, total_files, filename))
    
                    try:
                        with open(file_path, "rb") as in_f:
                            while True:
                                # Read the BSON document size
                                size_data = in_f.read(4)
                                if not size_data or len(size_data) < 4:
                                    break
    
                                # Parse the document size (little-endian)
                                doc_size = struct.unpack("<i", size_data)[0]
    
                                # Reread the complete document data
                                in_f.seek(in_f.tell() - 4)
                                doc_data = in_f.read(doc_size)
    
                                if len(doc_data) != doc_size:
                                    break
    
                                out_f.write(doc_data)
                    except Exception as e:
                        print("Error reading {}: {}".format(filename, str(e)))
        except Exception as e:
            print("Error in merge_single_bson_dir: {}".format(str(e)))
    
    def merge_bson_files_recursive(input_root: str, output_root: str = None) -> None:
        """
        Recursively traverses directories and merges all BSON files.
    
        Args:
            input_root (str): The root directory path containing the BSON files.
            output_root (str): The root directory for the output files, defaults to input_root.
        """
        if output_root is None:
            output_root = input_root
    
        # Ensure the output root directory exists
        if not os.path.exists(output_root):
            os.makedirs(output_root)
    
        print("Scanning directories in {}...".format(input_root))
        
        # Traverse all items in the input root directory
        for item in os.listdir(input_root):
            item_path = os.path.join(input_root, item)
            
            # If it is a directory, process it
            if os.path.isdir(item_path):
                print("Processing directory: {}".format(item))
                
                # Create the corresponding output directory
                output_item_path = os.path.join(output_root, item)
                if not os.path.exists(output_item_path):
                    os.makedirs(output_item_path)
                
                # Traverse all subdirectories and files within this directory
                for item_d in os.listdir(item_path):
                    sub_item_path = os.path.join(item_path, item_d)
                    for sub_item in os.listdir(sub_item_path):
                        data_path = os.path.join(sub_item_path, sub_item)
                        # If it's a "data" directory, merge the BSON files within it
                        if os.path.isdir(data_path) and sub_item == "data":
                            # Extract the namespace (parent directory name)
                            namespace = os.path.basename(sub_item_path)
                            merge_single_bson_dir(data_path, output_item_path, namespace)
                        # If it's a .metadata.json file, copy it directly to the corresponding output directory
                        elif sub_item.endswith(".metadata.json"):
                            src_file = os.path.join(sub_item_path, sub_item)
                            target_dir = os.path.join(output_item_path, sub_item)
                            shutil.copy(src_file, target_dir)
                            print("Copied metadata file: {}".format(sub_item))
                print("Finished processing directory: {}".format(item))
    
    if __name__ == "__main__":
        parser = argparse.ArgumentParser(description="Recursively merge BSON files")
        parser.add_argument("input_root", help="The root directory path containing the BSON files")
        parser.add_argument("-o", "--output_root", help="The root directory path for output files, defaults to the input root")
    
        args = parser.parse_args()
        merge_bson_files_recursive(args.input_root, args.output_root)

    Komutu çalıştırın:

    python merge_bson_files.py <input_directory> -o <output_directory>
  4. mongorestore aracını kullanarak yedek verileri kendi kendine yönetilen veritabanı örneğinize geri yükleyin.

    # Restore a single collection
    mongorestore --uri=<mongodb-uri> --db <db> --collection <collection>  <xxx.bson>
    # Example for a single collection
    mongorestore --uri='mongodb://127.x.x.x:27017/?authSource=admin' --db testDB --collection coll1 ./testDB/coll1.bson 
    # Restore a single database
    mongorestore --uri=<mongodb-uri> --db <db> --dir </path/to/bson/dir>
    # Example for a single database
    mongorestore --uri='mongodb://127.x.x.x:27017/?authSource=admin' --db testDB --dir ./testDB 
    # Restore an entire instance
    mongorestore --uri=<mongodb-uri>  --dir </path/to/bson/dir>
    # Example for an entire instance
    mongorestore --uri='mongodb://127.x.x.x:27017/?authSource=admin' --dir ./

    Parametreler:

    • <mongodb-uri>: Kendi kendine yönetilen veritabanınızın veya ApsaraDB for MongoDB örneğinizin bağlantı dizesi URI'si. URI, kullanıcı adını, parolayı, sunucu IP adresini ve bağlantı noktasını içerir. Daha fazla bilgi için bkz. resmi belgeler.

    • <db>: Geri yüklenecek veritabanının adı.

    • <collection>: Geri yüklenecek koleksiyonun adı.

    • <xxx.bson>: Geri yüklemek istediğiniz tek koleksiyona ait BSON yedek dosyası.

    • <path/to/bson/dir>: Geri yükleme işlemi için BSON dosyalarını içeren dizin.

SSS

Örnek türüm yedek dosyalarının indirilmesini desteklemiyorsa verileri kendi kendine yönetilen bir veritabanına nasıl geri yükleyebilirim?