Rvd*_*t23 8 python collections document 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()
Run Code Online (Sandbox Code Playgroud)
您可以生成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)
Run Code Online (Sandbox Code Playgroud)
你不能这样做,因为 MongoDB 没有内置模式。模式只是驱动程序的事情,即使如此,有些驱动程序支持它们,有些则不支持。
您可以尝试做的是创建一个简单的脚本来映射集合中文档中的所有字段,然后从中构造一个架构。
| 归档时间: |
|
| 查看次数: |
788 次 |
| 最近记录: |