【问题标题】:Mongoengine: update only specified fields on embedded documentMongoengine:仅更新嵌入文档上的指定字段
【发布时间】:2020-10-16 10:05:51
【问题描述】:

我有以下架构:

class Task(EmbeddedDocument):
    description = StringField()
    is_finished = BooleanField(default=False)

class Plan(DynamicDocument):
    priority = IntField()
    tasks = EmbeddedDocumentListField(Task)

然后我从字典创建一个计划实例(最初我是从 http 请求的 json 正文中获取字典):

body = {"priority": 1, "tasks": [{"description": "do this", "is_finished": true}]}

plan = Plan(**body).save()

然后我尝试更新任务嵌入文档的description,同时保持其其他字段is_finished 不变,同时保持计划的priority 字段不变:

new_body = {"tasks": [{"description": "do that"}]}
plan.update(**new_body)

但更新后is_finished 值更改为false(这是默认值)。

print(plan.to_json())
# prints {"priority": 1, "tasks": [{"description": "do that", "is_finished": false}]}

如何更新文档,同时保持未指定的嵌入字段不变,就像我对主文档上的 priority 字段所做的那样?我尝试从嵌入式文档模型中删除默认值,但如果在更新期间未指定该字段,我将完全删除该字段。

【问题讨论】:

    标签: python mongoengine


    【解决方案1】:

    这将更新特定字段

    plan.update(set__tasks__0__description='your new description')
    

    这里,0 是您要更新其描述的嵌入式文档(在“任务”列表中)的序数。

    【讨论】:

      猜你喜欢
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多