You can download this code by clicking the button below.
This code is now available for download.
This function uses PyMongoEngine to create a simple document class, randomly populates one field, and then saves it to the specified collection.
Technology Stack : PyMongoEngine, Document, StringField, BooleanField, random
Code Type : The type of code
Code Difficulty : Intermediate
from mongoengine import Document, StringField, BooleanField
from random import choice
def create_random_document(collection_name, document_data):
# Define a simple document class using PyMongoEngine
class RandomDocument(Document):
name = StringField()
is_active = BooleanField()
# Choose a random field to populate from the document_data dictionary
field_name = choice(list(document_data.keys()))
field_value = document_data[field_name]
# Create an instance of RandomDocument with the random field populated
random_document = RandomDocument(name=field_value, is_active=False)
random_document.save(collection_name)
return random_document
# JSON representation of the function