如何从现有集合中为mongoengine文档生成模型 [英] How to generate a model for a mongoengine Document from an already existing collection

查看:147
本文介绍了如何从现有集合中为mongoengine文档生成模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mongo中已有一个名为 students 的学生。有没有一种方法,我不必为所有字段输入模式,而直接从集合中导入所有字段?

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


推荐答案

您可以生成动态迭代文档的 user_properties (如此答案

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)

这篇关于如何从现有集合中为mongoengine文档生成模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆