Async MongoDB Connection with Motor Library

  • Share this:

Code introduction


This function uses the AsyncIOMotorClient class from the Motor library to asynchronously connect to a MongoDB database and return the database object.


Technology Stack : Motor, MongoDB, AsyncIOMotorClient

Code Type : Asynchronous MongoDB connection function

Code Difficulty : Intermediate


                
                    
from motor.motor_asyncio import AsyncIOMotorClient

async def connect_to_mongodb(uri, db_name):
    client = AsyncIOMotorClient(uri)
    db = client[db_name]
    return db