You can download this code by clicking the button below.
This code is now available for download.
This function creates a MongoEngine document, randomly sets the title, active status, and tags, and then saves it to the database.
Technology Stack : MongoEngine
Code Type : MongoEngine Document Creation
Code Difficulty : Intermediate
from mongoengine import Document, StringField, BooleanField, ListField
from random import choice
def create_random_document():
class RandomDocument(Document):
title = StringField()
is_active = BooleanField()
tags = ListField(StringField())
# Generate random data for the document
random_title = f"Random Title {choice(['A', 'B', 'C', 'D'])}"
random_is_active = choice([True, False])
random_tags = [f"Tag{choice(['1', '2', '3', '4'])}" for _ in range(3)]
# Create a new document with random data
new_document = RandomDocument(title=random_title, is_active=random_is_active, tags=random_tags)
new_document.save()
return new_document