How to remove a item from a list(ListField) by id in MongoEngine?

∥☆過路亽.° 提交于 2019-12-06 00:40:57

问题


structure:

{title: 'test', comments: [{id:1, title: ''}, {id: 8, title: ''}]}

i need remove the id=8 item, thanks.


回答1:


Hi you can pull items from an array:

https://github.com/hmarr/mongoengine/blob/master/tests/queryset.py#L1374

See $pull: http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull




回答2:


You need to use $pull operator here :

http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull

db.collection.update({'title':'test'},{$pull : { 'comments' : { 'id' : 8 }});



回答3:


Here is one example of the pull operator, using flask_mongoengine and assuming the parent object class is called Blog, and the comments are EmbeddedDocuments within Blog.

Blog.objects(id=blog_id).update_one(pull__comments___id=comment_id)

Notice the triple underscore in comments id. This is because if you want primary keys on Comments, you need to add one in your model declaration like this:

class Comment(db.EmbeddedDocument):
    _id = db.ObjectIdField(primary_key=True, default=lambda: ObjectId())
    ...

The lamba function will generate your primary keys for you.



来源:https://stackoverflow.com/questions/7846109/how-to-remove-a-item-from-a-listlistfield-by-id-in-mongoengine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!