Random Document Creation and Insertion

  • Share this:

Code introduction


This function creates a random document and inserts it into the specified collection. The function accepts a collection and a list of fields as parameters, generates random data based on the field list, and then saves it to the database.


Technology Stack : PyMongoEngine

Code Type : Database operation function

Code Difficulty : Intermediate


                
                    
def create_random_document(collection, fields):
    """
    This function generates a random document and inserts it into the given collection.
    """
    import random
    from mongoengine import Document, StringField, IntField

    # Define a simple document structure based on the provided fields
    class RandomDocument(Document):
        name = StringField()
        age = IntField()

    # Create a new instance of the document
    document = RandomDocument()

    # Randomly assign values to the fields based on the provided fields list
    for field in fields:
        if field == "name":
            document.name = f"Person{random.randint(1, 100)}"
        elif field == "age":
            document.age = random.randint(18, 65)

    # Save the document to the collection
    document.save()

    return document