There is an existing collection in mongo called students
. Is there a way where I don't have to type out the schema for all the fields and directly import all the fields from the collection?
class Student(DynamicDocument):
meta = {'collection': 'students'}
name = StringField() # I want to avoid writing this for all the fields in the collection
rollNo = IntField()
address = StringField()
You can generate user_properties
(as in this answer) dynamically iterating document by document in your collection and adding new values to that dict.
from pymongo import MongoClient
db = MongoClient(MONGODB_URI).get_database()
documents = db['users'].find()
user_properties = {
# Example of structure:
# '_id': StringField(required=False),
# 'name': StringField(required=False),
# 'email': StringField(required=False),
}
for doc in documents:
for field_name, value in doc.items():
# Some smart recognition can be here
field_definition = StringField(required=False)
user_properties[field_name] = field_definition
# Your new class for MongoEngine:
User = type("User", (Document, ), user_properties)
users = User.objects(email__endswith='.com')
print(users)
You can't do that as MongoDB doesn't have schemas built into it. Schemas are only a driver thing, and even then some drivers support them and some don't.
What you can try to do is create a simple script to map all the fields in the documents in your collection, then construct a schema out of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With