Skip to content

Instantly share code, notes, and snippets.

@ncocana
Created January 9, 2023 19:49
Show Gist options
  • Select an option

  • Save ncocana/591a26cd3d6f4b7bbb0a80cd0e1402b2 to your computer and use it in GitHub Desktop.

Select an option

Save ncocana/591a26cd3d6f4b7bbb0a80cd0e1402b2 to your computer and use it in GitHub Desktop.
Script in python to export all collections from a database in MongoDB.
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