Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a model for a mongoengine Document from an already existing collection

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()
like image 548
Rvdixit23 Avatar asked Jul 19 '20 11:07

Rvdixit23


2 Answers

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)
like image 144
wowkin2 Avatar answered Sep 18 '22 00:09

wowkin2


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.

like image 20
Dori Lahav Waisberg Avatar answered Sep 21 '22 00:09

Dori Lahav Waisberg