10

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

Or possibly delete it all and create it again?

Cisplatin
  • 2,642
  • 3
  • 30
  • 54

3 Answers3

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.

Community
  • 1
  • 1
Nauraushaun
  • 1,258
  • 11
  • 10
2
docker exec -it mongodb_container bash -c "mongo db-name --eval 'db.dropDatabase()'"
Matko
  • 3,325
  • 4
  • 19
  • 32
0

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();"'
tgogos
  • 19,659
  • 17
  • 88
  • 119