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

2019-04-07 06:48发布

structure:

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

i need remove the id=8 item, thanks.

3条回答
迷人小祖宗
2楼-- · 2019-04-07 07:26

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.

查看更多
甜甜的少女心
4楼-- · 2019-04-07 07:45

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 }});
查看更多
登录 后发表回答