Export and Import Collections from MongoDB with Docker in Kubernetes

j3ffyang
1 min readNov 17, 2021
This diagram is drawn with PlantUML (I love it)

When having a huge MongoDB in production and needing to backup, you may consider to just export (backup) a certain collections (tables) from database. Here’s a simple practice to export (and import) collection of MongoDB, running on Kubernetes.

The pre-requisite is to enable a service port-forward in Kubernetes, so you can access it through a Docker container.

kubectl -n sampleNameSpace port-forward svc/sample-sub-mongodb 27017:27017 &

For example, to export collection0 collection in NAMESPACE0 namespace

docker run --rm --name mongodb -v $(pwd):/app --net="host" \
bitnami/mongodb:latest mongoexport \
--host=127.0.0.1 --port=27017 \
-u root -p "$MONGODB_ROOT_PASSWORD" \
--authenticationDatabase "admin" \
--db sampledb --collection collection0__NAMESPACE0 \
--out=/app/collection0__NAMESPACE0.json --type json

To import a json. Notice the --collection=collection0__NAMESPACE0 which means collectionName=collection0 under nameSpace=NAMESPACE0

docker run --rm --name mongodb -v $(pwd):/app --net="host" \
bitnami/mongodb:latest mongoimport --host=127.0.0.1 --port=27017 \
-u root -p "$MONGODB_ROOT_PASSWORD" \
--authenticationDatabase "admin" --db sampledb \
--collection \ collection0__NAMESPACE0 \
--file=app/collection0__NAMESPACE0.json --type json

> Pay attention to the formatType of import and export

--

--

j3ffyang
j3ffyang

Written by j3ffyang

ardent linux user, opensource, kubernetes containerization, blockchain, data security. handler of @analyticsource and @j3ffyang

No responses yet