Asynchronous MongoDB Data Insertion with Beanie and Motor

  • Share this:

Code introduction


This function uses the Beanie and Motor libraries for asynchronous MongoDB operations to create a simple MongoDB collection and insert a randomly generated data into it.


Technology Stack : Beanie, Motor, AsyncIOMotorClient

Code Type : Asynchronous database operation

Code Difficulty : Intermediate


                
                    
def random_beanie_function():
    import beanie
    import random
    import motor.motor_asyncio

    class RandomDataBean(beanie.Document):
        value: str

    async def create_random_data():
        client = motor.motor_asyncio.AsyncIOMotorClient('localhost', 27017)
        db = client['random_db']
        collection = db['random_collection']

        # Randomly select a value and insert it into the database
        random_value = random.choice(['apple', 'banana', 'cherry', 'date', 'elderberry'])
        random_data = RandomDataBean(value=random_value)
        await collection.insert_one(random_data)

    return create_random_data