You can download this code by clicking the button below.
This code is now available for download.
This function creates a random document and saves it to a specified MongoDB collection. The function accepts a database instance, a collection name, and field definitions, and generates random values based on the field types.
Technology Stack : PyMongoEngine, MongoDB
Code Type : PyMongoEngine Document Creation
Code Difficulty : Intermediate
def create_random_document(db, collection_name, fields):
"""
This function creates a random document in a specified collection using given fields.
:param db: The database instance.
:param collection_name: The name of the collection where the document will be created.
:param fields: A dictionary of field names and their corresponding field types.
"""
# Import the required PyMongoEngine classes
from mongoengine import Document, fields as mongoengine_fields
# Create a custom Document class based on the provided fields
class RandomDocument(Document):
__name__ = collection_name
for field_name, field_type in fields.items():
if field_type == "StringField":
locals()[field_name] = mongoengine_fields.StringField(field_name)
elif field_type == "IntField":
locals()[field_name] = mongoengine_fields.IntField(field_name)
elif field_type == "FloatField":
locals()[field_name] = mongoengine_fields.FloatField(field_name)
elif field_type == "DateTimeField":
locals()[field_name] = mongoengine_fields.DateTimeField(field_name)
elif field_type == "ListField":
locals()[field_name] = mongoengine_fields.ListField(
mongoengine_fields.StringField(), field_name
)
# Create a random document and save it to the database
random_document = RandomDocument()
for field_name, field_type in fields.items():
if field_type == "StringField":
random_document[field_name] = "RandomString"
elif field_type == "IntField":
random_document[field_name] = random.randint(1, 100)
elif field_type == "FloatField":
random_document[field_name] = random.uniform(1.0, 100.0)
elif field_type == "DateTimeField":
random_document[field_name] = datetime.now()
elif field_type == "ListField":
random_document[field_name] = [f"Item{i}" for i in range(5)]
random_document.save()
# Example usage
db = 'your_database'
collection_name = 'random_documents'
fields = {
'name': 'StringField',
'age': 'IntField',
'score': 'FloatField',
'timestamp': 'DateTimeField',
'tags': 'ListField'
}
create_random_document(db, collection_name, fields)