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

Structure

:

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

I need to remove the id = 8 element, thanks.

+7
source share
3 answers

You need to use the $ pull operator here:

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

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

Here is one example of a pull statement using flask_mongoengine and assuming the parent class is called Blog and the comments are EmbeddedDocuments on the blog.

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

Note the triple underscore in the id comment. This is because if you need primary keys in the comments, you need to add them to the model declaration as follows:

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

The lamba function will generate your primary keys for you.

0
source

All Articles