MongoDB + Docker

MongoDB is not your typical database. It is a NoSQL variant that stores data in an document based format. There are several advantages and disadvantages that I will not go into details in this post. In this document we will go over how to quickly setup a MongoDB instance inside an docker container along with adding data and running a query against it.

Downloading the Pre-existing Mongo container.

sudo docker pull mongo

Create Your Mount Partition

Docker containers are volatile. This means that when you shutdown the container any changes to any of the files inside a container are lost. The default Mongo container mounts the databases under the /data/db path. We can map that path with a path on the physicals host with the below command.

Create a directory to store your data with the following command.

sudo mkdir -p /data/mongo

When you run the container you will want to map the /data/mongo directory path with /data/db using the following command.

-v /data/mongo:/data/db

Run Mongo

sudo docker run -it -v /data/mongo:/data/db -p 27017:27017 --name mongodb -d mongo

Check Status

sudo docker ps

Connect to MongoDB From Python

There are several ways that you could perform CRUD operations on a MongoDB. We will be using Python in this document. We will start by installing pymongo.

python -m pip install pymongo 

Below is a full python script to add Data customers to a document named customer.

import pymongo

myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017/")

mydb = myclient["mydatabase"]

mycol = mydb["customers"]

mydict = {"name":"Harrison","address 	One Microsoft Way", "city":"Redmond","state":"Washington"}

#mycol.insert_one(mydict);

#Let's insert a customer and print the inserted ID.
x = mycol.insert_one(mydict);
print(x.inserted_id)


#Lets Find just one. 
x = mycol.find_one()
print(x)

#Find All

for y in mycol.find():
        print(y)

print("Finding by Query")
print(".")
print(".")
print(".")

#The following query can search full or regex for example
#myquery = {"name":"Harrison"}
#Searching for regex
myquery = {"name": { "$regex": "^H" }} 

mydoc = mycol.find(myquery)

for x in mydoc: 
        print(x)

In this document we went over how to quickly get a Mongo Docker container up and running with a quick script for adding and querying data to a Mongo database.

Quick About

Hi, I am Michael Harrison. Devops/Developer for day job and father full time. I like machines such as 3d printers and like designing items for them.

Contact


E-mail: [email protected]
Phone: (765) 421-6199

Other Information


[Construction Icon]