You can download this code by clicking the button below.
This code is now available for download.
This function uses PyMongoEngine to create a random document and save it to the database. It randomly selects a field (name or is_active) and assigns a random value to it.
Technology Stack : PyMongoEngine
Code Type : Function
Code Difficulty : Intermediate
from mongoengine import Document, StringField, BooleanField
from random import choice
def create_random_document():
class RandomDocument(Document):
name = StringField()
is_active = BooleanField(default=True)
# Randomly choose a field to update
fields = ['name', 'is_active']
field_to_update = choice(fields)
# Create a new document with a random value for the chosen field
new_document = RandomDocument(**{field_to_update: choice(['John Doe', 'Jane Doe', True, False])})
new_document.save()
return new_document