[英]How to update/delete embeded document in ListField based on its ID mongoengine?
我有以下文件:
class Note(EmbeddedDocument):
value = mongo_db.StringField(max_length=200, required=True)
id = mongo_db.UUIDField(required=True, primary_key=True)
class Post(Document,):
notes = mongo_db.ListField(mongo_db.EmbeddedDocumentField(Note))
如何编写一条语句来更新Post
object 列表中的Note
object 的value
字段。 换句话说,如何编写执行以下操作的内容:
update(post_id, note_id, new_valye)
以类似的方式,我如何删除嵌入文档的实例Note
:
delete(post_id, note_id)
首先,我编辑了 My Post
Document 以获得EmbeddedDocumentListField
的好处:
class Note(EmbeddedDocument):
value = mongo_db.StringField(max_length=200, required=True)
id = mongo_db.UUIDField(required=True, primary_key=True)
class Post(Document,):
notes = mongo_db.EmbeddedDocumentListField(Note, required=False)
然后用于更新:
Post.objects(
id=post_id,
notes__id=note_id
).update(
set__notes__S__value=my_value
)
对于删除:
Post.objects(id=post_id).update_one(
pull__notes__id=note_id
)
但是我认为,这种方法存在一个问题,如果您要更新许多字段,现在很难编写第一次更新。
您有两种方法可以做到这一点,假设您要更新列表的第二项(即在 index=1 处):
1)获取您的文档实例并使用.save()
post = Post.objects().first()
post.notes[1].value = 'new_value'
post.save()
2)如果您只需要更新文档的字段,并且您知道数组中的 position,那么您可以使用:
Post.objects.update(set__notes__1__value='new_value')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.