Dockerized MongoDB for use with PyMongo

Just the other day, I found myself needing to use MongoDB. The go to choice of toolkit for Python developers seems to be PyMongo, so I wanted to have a little play around this library, just to get a feel. The problem in situations like this, however, is that you actually need to get a database to connect to! And that’s a not insignificant feat... Whenever learning something new, I’ve often ended up clogging up my computers with installations of software that I hardly use, different tooling related to it, and in the case of databases, the actual files themselves eating up storage. 

This is obviously a problem that containerisation,(and in particular Docker), solves. Its ephemeral, so it goes away once you've finished, and its decoupled from your operating system, so nothing gets too 'interfered with'. I'm not declaring anything revolutionary here; this blog post is more documentation for myself, for when I need to go back and do this again at a later date. Hopefully its useful for someone with the same problem as me! 


(Im assuming, by the way, that you have Docker installed!?) 

Open up a bash terminal and type: 

sudo docker run -it --name mongodb -p 27017:27017 -d mongo

This pulls the image for MongoDB, (if it doesn't exist locally), builds and runs it, mapping the ports. 

Next we want to open up a bash session actually inside the running Mongo container

docker exec -it mongodb bash

Now that you're in a terminal, (inside of your terminal), type 'mongo' to open up the interactive MongoDB shell.

show dbs

This command will show you what databases come out the box:

admin 0.000GB

config 0.000GB 

local 0.000GB

So you can see we have 3 databases with nothing in them. We want to use the admin database, because thats from where Mongo manages user accounts and access, etc. 

use admin

Switches the shell to work on the admin db and then we can create an admin user, like so:

db.createUser({user: "username",pwd: "password",roles: [ "root" ]})

Exit out of the shell(s), if you so wish, and we now have a MongoDB instance running on port 27017 of our localhost, with an admin user whose credentials we know.

Now we can easily explore the PyMongo interface, here is a trivial script: 

import pymongo

# create the connection from the PyMongo client to the MongoDB server
conn = pymongo.MongoClient(
    "localhost",
    27017,
    username="username",
    password="password",
    connect=True,
    authSource="admin",
)

# create a database called 'example'
db = conn.example
# create a collection in example called 'my_collection'
my_collection = db.my_collection
# insert a single document into 'my_collection'
my_collection.insert_one({"test": "ing"})
# retrieve the document
val = 'ing'
my_collection.find_one({"test":val})

 

 

You may also like: