Asynchronous Document Insertion into MongoDB Collection Using Beanie and Motor

  • Share this:

Code introduction


This function uses the Beanie and Motor asynchronous libraries to insert a randomly generated document into a specified MongoDB collection.


Technology Stack : Beanie, Motor, MongoDB

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
from beanie import Document, PydanticObjectId
from motor.motor_asyncio import AsyncIOMotorClient

def random_document_insert(collection_name, data):
    """
    Inserts a random document into a specified MongoDB collection using Beanie and Motor.
    """
    # Create a MongoDB client
    client = AsyncIOMotorClient('mongodb://localhost:27017')
    
    # Get the specified collection
    collection = client['mydatabase'][collection_name]
    
    # Create a document from the data provided
    document = Document(**data)
    
    # Insert the document into the collection
    await collection.insert_one(document)
    
    # Close the MongoDB client connection
    client.close()

# Example usage
if __name__ == "__main__":
    # Define some example data
    example_data = {
        'name': 'John Doe',
        'age': 30,
        'email': 'john.doe@example.com'
    }
    
    # Call the function with a random collection name and example data
    random_document_insert('random_collection', example_data)