What is the best way to take backups of mongo collections?

244 Views Asked by At

I need to write a function to take up a backup of mongo collections that would be in a configurable list.

String listOfCollectionsToBackup = "collection1,collection2,collection3";

I need a way to fetch all the data from these tables and write it in a text file. The current way I am doing this is checking for the collection name and having a switch case to access various classes defined.

@Autowired
MongoTemplate mongoTemplate;

// some code

for(String collection : listOfCollectionsToBackup.split(","){
   switch(collection){
      case "collection1" : 
         mongoTemplate.findAll(Collection1.class); 
         //write data to file

      case "collection2" : 
         mongoTemplate.findAll(Collection2.class); 
         //write data to file

      case "collection3" : 
         mongoTemplate.findAll(Collection1.class); 
         //write data to file

      case "collection3" : 
         //error message
   }
}

Since I indend to have the listOfCollectionsToBackup is intended to be configurable and I plan to have new collections not yet created, I want a way to do it as generically as possible.

I am using Springboot version 2.4.2 And I am using spring-boot's MongoTemplate to access the DB.

What is the most efficient way to do this? Any help is appreciated. Thanks!

1

There are 1 best solutions below

4
Waged On

Backups of MongoDB collections can be done in several ways, all depend on your specific requirements and how big the project is and the tools you prefer to use. Here's my approach to achieve this task:

Use MongoDB Utilities: You can run it from the command line to create backups of specified collections or the entire database.

mongodump --db your_database_name --collection collectionX --out /path/to/backup/directory

You can write a script in your preferred language to automate this process by iterating over the list of collections to back up.

i use python script like this :

from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017')
db = client.your_database_name

collections_to_backup = ["collection1", "collection2", "collection3"]

for collection_name in collections_to_backup:
    collection = db[collection_name]
    cursor = collection.find()

    with open(f"{collection_name}.txt", "w") as file:
        for document in cursor:
            file.write(str(document) + "\n")