结构体:
{title: 'test', comments: [{id:1, title: ''}, {id: 8, title: ''}]}
我需要删除 id=8 项目,谢谢。
结构体:
{title: 'test', comments: [{id:1, title: ''}, {id: 8, title: ''}]}
我需要删除 id=8 项目,谢谢。
嗨,您可以从数组中提取项目:
https://github.com/hmarr/mongoengine/blob/master/mongoengine/queryset.py
见 $pull:http ://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
您需要在此处使用 $pull 运算符:
http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
db.collection.update({'title':'test'},{$pull : { 'comments' : { 'id' : 8 }});
这是拉操作符的一个示例,使用flask_mongoengine 并假设父对象类称为Blog,并且评论是Blog 中的EmbeddedDocuments。
Blog.objects(id=blog_id).update_one(pull__comments___id=comment_id)
注意评论 id 中的三个下划线。这是因为如果您想要 Comments 上的主键,您需要在模型声明中添加一个,如下所示:
class Comment(db.EmbeddedDocument):
_id = db.ObjectIdField(primary_key=True, default=lambda: ObjectId())
...
lamba 函数将为您生成主键。