Integrate MongoDB With Python

ZennDogg
2 min readMay 23, 2022
Photo by Pawel Czerwinski on Unsplash

Several apps I code use a database. Many databases can be coupled with Python. Most of the compatible databases are either SQL-based or document-based. I prefer a document-based database called MongoDB. MongoDB is a bit intensive to learn but a breeze to use.

Since I use a database for over half of my projects, I wrote a helper function to import and initialize it. In the past, this function was rewritten a few times. This is the latest iteration.

from pymongo import MongoClient

Pymongo, a module available on pypi.org, is a native Python driver for MongoDB. The first step when working with PyMongo is to create a MongoClient for the running MongoDB instance. After a long brainstorming session, I decided to name my function db().

def db(database_name: str:, collection_name: str, *args: str)->str:

The function initializes the name of the database and the name of the collection, or table. I use *args to initialize additional tables, as needed.

client = MongoClient('localhost', 27017)

MongoClient requires a mongo server and a port. Starting the mongo server will be covered later in this article. The default port is nearly always 27017.

db = client[f"{database_name}"]

This line of code designates the name of the database.

collection = db[f"{collection_name}"]

And this line of code designates the name of the collection.

if not args:
return collection

If *args is null, that means we are initializing one collection.

else:
colls = [db[f"{arg}"] for arg in args]
colls.insert(1, collection)
return colls

However, if there are additional collections, then we need to connect those as well. The first line above uses list comprehension to assign the args to individual collections. they are then appended to the list colls. Now that we have iterated through the *args, we need to insert the original collection_name. Lastly we return the list of collections, finalizing the connection to the MongoDB server.

def db(database_name: str, collection_name: str, *args: str)->str:
"""
Intitializes MongoDb database

:param database_name: Name of db
:param collection_name: Collection (table) name
:param *args: Additional collection names, as needed
"""

client = MongoClient('localhost', 27017)
db = client[f"{database_name}"]
coll = db[f"{collection_name}"]
if not args:
return coll
else:
colls = [db[f"{arg}"] for arg in args]
colls.insert(1, coll)
return colls

Running the MongoDB Server

Download the MongoDB installation package and run it. Change directory to \MongoDB\Server\4.2\bin\. I chose to start the server from the command line (cli). The command is mongod.exe.

I use a batch file to start MongoDb and Python among other apps. This is the excerpt from that batch file.

@cd C:\Program Files\MongoDB\Server\4.2\bin\
@start /min mongod.exe

I hope you enjoyed this article. You can find more like this at my website. While there, please visit our advertiser’s page. I make a small commission on any purchase. That money is used to run and maintain the site. Cheers!

--

--

ZennDogg

Retired military, Retired US Postal Service, Defender of the US Constitution from all enemies, foreign and domestic, Self-taught in python