Random Document Creation with PyMongoEngine and MongoDB

  • Share this:

Code introduction


This function uses PyMongoEngine to create a document with random data and saves it to the specified collection. It uses MongoDB as the database.


Technology Stack : PyMongoEngine, MongoDB, MongoClient, Document, StringField, IntField, ListField

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
def create_random_document(collection, data):
    """
    This function generates a random document and saves it to the specified collection.
    """
    import random
    from pymongo import MongoClient
    from mongoengine import Document, StringField, IntField, ListField

    # Define the Document structure using PyMongoEngine
    class RandomDocument(Document):
        name = StringField()
        age = IntField()
        hobbies = ListField(StringField())

    # Connect to the MongoDB server
    client = MongoClient('localhost', 27017)
    db = client['random_db']

    # Create a new document with random data
    random_document = RandomDocument(
        name=random.choice(['Alice', 'Bob', 'Charlie']),
        age=random.randint(18, 60),
        hobbies=random.sample(['Reading', 'Swimming', 'Hiking', 'Coding'], 3)
    )

    # Save the document to the specified collection
    random_document.save(collection=db[collection])

    # Return the saved document
    return random_document