Random Document Creation and MongoDB Storage

  • Share this:

Code introduction


This function creates a random document and stores it in a MongoDB database. The document includes a title, description, and tags.


Technology Stack : Beanie, Motor, PydanticObjectId, fields, AsyncIOMotorClient

Code Type : The type of code

Code Difficulty : Intermediate


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

# Define a custom function using Beanie and Motor
def create_random_document(collection_name):
    # Create a random document
    document = Document(
        title=random.choice(["Python", "Java", "C++", "JavaScript"]),
        description=random.choice(["A programming language", "An interpreted language", "A compiled language", "A scripting language"]),
        tags=random.sample(["Web", "Mobile", "Desktop", "DevOps", "Data Science"], k=2)
    )
    
    # Insert the document into the specified collection
    client = AsyncIOMotorClient("mongodb://localhost:27017/")
    db = client["mydatabase"]
    collection = db[collection_name]
    await collection.insert_one(document)
    
    return document

# JSON representation of the code