You can download this code by clicking the button below.
This code is now available for download.
This function dynamically creates a new MongoDB document class based on the provided field definitions, generates random values for each field, and then saves the document to the specified MongoDB collection.
Technology Stack : PyMongoEngine, mongoengine, mongomock, random, datetime
Code Type : The type of code
Code Difficulty : Intermediate
def generate_random_document(collection, fields):
"""
Generates a random document for a given MongoDB collection and field definitions.
Args:
collection (mongomock.collection): The MongoDB collection to insert the document into.
fields (dict): A dictionary defining the fields and their types for the document.
"""
import random
from mongomock import collection
from mongoengine import Document, fields
# Create a new document class dynamically based on the fields provided
class RandomDocument(Document):
__abstract__ = True
for field_name, field_type in fields.items():
field = field_type()
field.name = field_name
setattr(RandomDocument, field_name, field)
# Instantiate the document with random values for each field
document = RandomDocument()
for field_name in fields:
field_type = fields[field_name]
if field_type == fields.IntField:
setattr(document, field_name, random.randint(1, 100))
elif field_type == fields.StringField:
setattr(document, field_name, "random_string")
elif field_type == fields.DictField:
setattr(document, field_name, {"key": "value"})
elif field_type == fields.ListField:
setattr(document, field_name, [1, 2, 3])
elif field_type == fields.DateTimeField:
setattr(document, field_name, random.datetime())
# Save the document to the collection
collection.insert_one(document)