url连接mongo
connect()或register_connection()
连接多个数据库时需要设置alias
connect(host='mongodb://119.23.10.188:61452/golem')
register_connection(alias='golem', db='golem', host='mongodb://119.23.10.188:61452/golem')
编写Models/Objects
from mongoengine.document import Document
from mongoengine.document import EmbeddedDocument
from mongoengine import fields
class Rules(EmbeddedDocument):
target_backup_vault_id = fields.StringField(required=True)
lifecycle = fields.DictField(required=True)
schedule_expression = fields.StringField(required=True)
rule_name = fields.StringField(required=True)
start_windows_minutes = fields.IntField(required=True)
completion_windows_minutes = fields.IntField(required=True)
class Plan(Document):
name = fields.StringField(nullable=True)
description = fields.StringField(nullable=True)
project_id = fields.StringField(nullable=True)
created_at = fields.DateTimeField(nullable=True)
last_execution_date = fields.DateTimeField(nullable=True)
rules = fields.EmbeddedDocumentField(Rules, nullable=True)
meta = {
'db_alias': 'golem',
'collection': 'plans',
'indexes': [
{
'fields': ['project_id'],
'name': 'project_idx'
}
]
}
特殊Document类型:
DynamicDocument 动态document,可以动态增加属性
EmbeddedDocument 嵌入document,只能作为其余document的属性类型,不会创建表
特殊Field类型:
EmbeddedDocumentField 使用EmbeddedDocument 作为参数
ReferenceField 使用其他已知document作为参数
GenericReferenceField 使用其他未知document作为参数
创建表/保存数据
调用save()时,若对象无id或id不存在时会新建数据,若对象有id且数据库存在时会修改数据
values = {
"name": "plan",
"project_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"description": "test plan",
"rules": {
"target_backup_vault_id": "string",
"lifecycle": {
"delete_after_days": 365
},
"schedule_expression": "cron(0 5 ? * * *)",
"rule_name": "string",
"start_windows_minutes": 0,
"completion_windows_minutes": 0
},
"created_at": "2021-12-31T08:49:35.832Z",
"last_execution_date": "2021-12-31T08:49:35.832Z"
}
rule = Rules(**values.pop('rules'))
plan = Plan(**values, rules=rule)
plan.save()
plan.description = 'new plan'
plan.save()
查询数据
Document
Plan.objects()
Plan.objects(name='plan')
Plan.objects(id='id').first()
更新数据
使用update()或者save()
plan = models.Plan.objects(id=id).first()
plan.update(**values)
plan = model.Plan(**values, id=id)
plan.save()
|