What's new

Python MongoDB Backup

Nepyoo

Forum Guru
Elite
Joined
Jun 14, 2014
Posts
822
Solutions
7
Reaction
6,450
Points
1,065
I got a fresh instance of MongoDB with better specs than what I currently use. Provide a working example of transporting data from one uri to another with specified database and collection name using global variables containing env credentials each at the top using replace_one() object sorted by its native ID assignment "_id" in Python 3.9.
 
Sure, here's an example Python script that uses the PyMongo driver to retrieve data from one MongoDB instance and insert it into another:

Python:
import pymongo
import os

# Set up the source and destination MongoDB URIs
src_uri = os.environ['SRC_URI']
dst_uri = os.environ['DST_URI']

# Set up the source and destination database and collection names
src_db_name = 'source_db'
dst_db_name = 'destination_db'
collection_name = 'my_collection'

# Connect to the source and destination MongoDB instances
src_client = pymongo.MongoClient(src_uri)
dst_client = pymongo.MongoClient(dst_uri)

# Retrieve data from the source MongoDB instance
src_collection = src_client[src_db_name][collection_name]
src_data = src_collection.find().sort('_id', pymongo.ASCENDING)

# Insert data into the destination MongoDB instance
dst_collection = dst_client[dst_db_name][collection_name]
for document in src_data:
    dst_collection.replace_one({'_id': document['_id']}, document, upsert=True)

In this example, the script retrieves data from a collection named my_collection in a source MongoDB instance specified by the SRC_URI environment variable. It then inserts that data into a collection with the same name in a destination MongoDB instance specified by the DST_URI environment variable. The data is sorted by the _id field in ascending order, and is inserted into the destination collection using the replace_one() method with the upsert option set to True to insert new documents and update existing ones.
 
Back
Top