Created
January 9, 2023 19:49
-
-
Save ncocana/591a26cd3d6f4b7bbb0a80cd0e1402b2 to your computer and use it in GitHub Desktop.
Script in python to export all collections from a database in MongoDB.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| # Exports JSON files of each collection in the database in MongoDB. | |
| def exportJsonMongo(): | |
| # Fill the variables with the data from your Mongo Cluster. | |
| atlas_uri = "mongodb+srv://nameCluster.codeCluster.mongodb.net/database" | |
| username = "username" | |
| password = "password" | |
| directory_to_export = "./folder" | |
| # Creates a list with the names of each collection. | |
| # Write the name of the collections of the database you're going to export them from. | |
| all_collections = ["collection1","collection2","collection3","collection4","collection5"] | |
| # Executes the following for each collection in the variable "all_collections". | |
| for collection in all_collections: | |
| # Creates a variable called "command" with the command to export a collection from MongoDB | |
| # and passes it the variables defined above. | |
| command = 'mongoexport --uri="{0}" --username {1} --password {2} --collection={3} --out={4}/{3}.json'.format(atlas_uri, username, password, collection, directory_to_export) | |
| # Executes the command in the variable "command" with the passed variables as if it was executed in the terminal. | |
| os.system(command) | |
| if __name__ == "__main__": | |
| exportJsonMongo() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment