Connecting to MongoDB with Motor Async Driver

  • Share this:

Code introduction


This function connects to a MongoDB database using Motor, an asynchronous driver for MongoDB, and returns the database object.


Technology Stack : Motor, MongoDB

Code Type : Function

Code Difficulty : Intermediate


                
                    
from motor.motor_asyncio import AsyncIOMotorClient

def connect_to_mongodb(uri, database_name):
    """
    Connect to MongoDB using Motor, an async driver for MongoDB
    """
    client = AsyncIOMotorClient(uri)
    db = client[database_name]
    return db                
              
Tags: