python - 如何从已经存在的集合中为 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()
解决方案
您可以生成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)
推荐阅读
- c++ - 空对象正在调用一个方法,但程序没有崩溃……如何……为什么?
- vba - 扫雷的 VBA 随机地雷生成
- javascript - 循环遍历对象数组时调用方法
- pm2 - PM2 能否对标记为“错误”的进程采取措施
- android - 如何使用设备的加速度计检测运动增加然后突然停止?
- eigen - 对包含固定大小的 Eigen 类型的结构使用默认的 Eigen::aligned_allocator 是否危险?
- ms-access - 在 Access VBA 中抓取项目并将其从一种形式返回到另一种形式
- ios - Swift 在 UITableViewCells 中保留 UISegmentedControl 值
- neural-network - 如何反转 AvgPool2d?
- c++ - 浮点值上的否定运算符与 boost::math::changesign