11

Is there an easy way to clear a mongodb database running in docker?

Or possibly delete it all and create it again?

2
  • 2
    Can't you just remove the container and recreate another one? Commented Jun 24, 2016 at 17:48
  • 2
    For reference, docker container ls --all then docker container rm <id>, then build again Commented Jun 23, 2019 at 19:07

3 Answers 3

8

There are a number of ways:

  • The same way you would normally clear a mongodb database. You're running it in Docker, but it is a real mongodb after all. See this, and this.
  • If you've mounted your database's data as a volume on the host system using -v on the docker run command, you can just clear this folder out.
  • If you haven't, the data lives in the container. You can remove the container and recreate it (docker rm container_name). Or run a shell in the container and remove the data from the container's filesystem (docker exec -it container_name bash).

Regarding the last option, you shouldn't be in this scenario because your data should live on the host system and your container should be disposable.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also delete volumes using docker volume rm <volume_name>
4
docker exec -it mongodb_container bash -c "mongo db-name --eval 'db.dropDatabase()'" 

Comments

1

I had a case with slightly different requirements:

  • docker-compose
  • authentication needed
  • bash variable expansion (the container was running with environemt variables MONGO_USER & MONGO_PASSWORD already set)

So, for anyone who might need a handy one-liner to authenticate and drop a mongo db with docker, here it is 👇:

docker-compose exec mongo_container_name /bin/bash -c 'mongo database_name -u $MONGO_USER -p $MONGO_PASSWORD --authenticationDatabase admin --eval "db.dropDatabase();"' 

And if you add a Makefile to the "mix", it's exactly the same but it needs $$ to the variables:

db-reset: docker-compose exec mongo_container_name /bin/bash -c 'mongo database_name -u $$MONGO_USER -p $$MONGO_PASSWORD --authenticationDatabase admin --eval "db.dropDatabase();"' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.