问题
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