Install MongoDB with Docker (in Ubuntu 18.04)
Sandeep Chahal
Thursday, November 26 2020
1
Firstly, create the mapping repository for mongodb:
mkdir ~/docker/mongo_8301
mkdir ~/docker/mongo_8301/db
mkdir ~/docker/mongo_8301/config
mkdir ~/docker/mongo_8301/log
Then create the launch file for starting the docker container:
touch ~/launchers/docker_mongo_8301.sh
vi ~/launchers/docker_mongo_8301.sh
Fill the following code into the launch file:
docker rm -f mongo_docker_8301
docker run -d -p 8301:27017 \
--name mongo_docker_8301 \
-v /home/jemaloQ/docker/mongo_8301/config:/data/configdb \
-v /home/jemaloQ/docker/mongo_8301/db:/data/db \
-v /home/jemaloQ/docker/mongo_8301/log:/data/log \
mongo --auth
Now launch docker using cmd line sh ~/launchers/docker_mongo_8301.sh. Wait till the end of image pull. Then check if mongo_docker_8301 is running correctly by executing docker ps -a | grep mongo.
Enter the inside of the container and execute mongo admin to login the default 'admin' database
docker exec -it mongo_docker_8301 mongo admin
Now try to connect the newly launched MongoDB by Python:
from pymongo import MongoClient
client = MongoClient("mongodb://jemaloQ:123456@111.22.123.117:8301")
# print all the Databases names in Mongodb, returns empty list if no database has been created
client.list_database_names()
# connect to the 'knowledge' database, if it does not exist, this line shall create it and then connect to it
db = client['knowledge']
# get the 'test' collection of the 'knowledge' database, if it does not exist, this line shall create it
col = db.get_collection('test')
# this item shall be uploaded to my database
item_dic = {'uid': 123, 'name': 'jemaloQ'}
# a query filter for checking whether an item with same id exists or not
query_filter = {"uid": item_dic["uid"]}
# now insert the item to 'test' collection of knowledge' database
col.update( query_filter, {'$setOnInsert': item_dic}, upsert=True)
# now, we can see the 'knowledge' database since it is no longer empty
client.list_database_names() # => ['knowledge']