connect()或register_connection()
连接多个数据库时需要设置alias
connect(host='mongodb://119.23.10.188:61452/golem')
# 连接多个数据库时需要设置alias
# connect(host='mongodb://119.23.10.188:61452/octopus', alias='octopus')
register_connection(alias='golem', db='golem', host='mongodb://119.23.10.188:61452/golem')
# Copyright 2021 EasyStack, Inc.
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对象无id,此时会新建表,新建数据,新建后会自动赋值新id
plan.description = 'new plan'
plan.save() # plan对象已有id,此时会修改数据
Document
# 获取所有
Plan.objects()
# 条件查询
Plan.objects(name='plan')
# 根据id查询一个
Plan.objects(id='id').first()
使用update()或者save()
# 根据id查询到原数据,再update
plan = models.Plan.objects(id=id).first()
plan.update(**values)
# 直接使用新数据创建
plan = model.Plan(**values, id=id)
plan.save()