首页 > 解决方案 > 如何从已经存在的集合中为 mongoengine 文档生成模型

问题描述

mongo 中有一个名为students. 有没有一种方法,我不必为所有字段输入架构并直接从集合中导入所有字段?

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()

标签: pythoncollectionsdocumentmongoengine

解决方案


您可以生成user_properties(如在此答案中)动态迭代集合中的文档并向该字典添加新值。

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)

推荐阅读