Installing Mongo DB instance on Docker for Windows using a JSON file

Installing Mongo DB instance on Docker for Windows using a JSON file

Docker

If not installed download Docker. To check go to your command-line terminal like Git Bash and run
//to check the version.
docker version
//verify that Docker can pull and run images
docker run hello-world

Set up

I assume you have Docker installed and are using Linux (not Windows) containers. I am running a Windows-specific version of desktop for community. Now let's create a volume to persit data, otherwise anything you do will vanish after the container stops running
docker volume create --name=mongodata
Open Git Bash and type
docker volume create --name=mongodata
Now lets create a Mongo container. This may take a while for the first run.
docker run --name mongodb -v mongodata:/data/db -d -p 27017:27017 mongo

Mongo

Download some sample JSON to import from here. Login to the Mongo instance, in your Git Bash run
winpty docker exec -it mongodb bash
//This should show
root@8711e0054d0a:/#
Then open a MongoDB Terminal by typing:
mongo
You now have access to the DB.

Import

Exit out of everything and change directory to where the json file was saved to earlier, run the following in Git Bash
winpty docker cp database.json mongodb:database.json
Now run
winpty docker exec -it mongodb bash
ls
//You should see your database.json in there
Now to import this data into your DB, exit back to Git Bash Command line and run
winpty docker exec mongodb mongoimport -d testdbname -c mongoCfg1 --file database.json

Testing

Now lets see the database in our system, from Git Bash command line to login
winpty docker exec -it mongodb mongo
Once you are logged in type
show dbs

admin       0.000GB
config      0.000GB
local       0.000GB
testdbname  0.002GB
Here you can see our testdbname with some data.To select it type
use testdbname
switched to db testdbname
Now show the collections by typing
show collections mongoCfg1
Now lets show the data in that collection
db.mongoCfg1.find()

Categories: Posts