Applying the PyMongo driver for synchronous connections
We will start by learning how the FastAPI application connects to MongoDB using the PyMongo database driver. This driver is equivalent to psycopg2
, which allows us to access PostgreSQL without using any ORM. Some popular ODMs, such as MongoEngine and Motor, use PyMongo as their core driver, which gives us the reason to explore PyMongo first before we touch on issues regarding popular ODMs. Studying the driver’s behavior can provide baseline transactions that will show how an ODM builds the database connectivity, models, and CRUD transactions. But before we proceed with the details, we need to install the pymongo
extension using pip
:
pip install pymongo
Setting up the database connectivity
PyMongo uses its MongoClient
module class to connect to any MongoDB database. We instantiate it with the specified host and port to extract the client object, such as MongoClient("localhost", "27017")
, or...