我想在ListField中添加一个元素。这是我的代码:
class Post(Document):
_id = StringField()
txt = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
class Comment(EmbeddedDocument):
comment = StringField()
comment_id = StringField()
...
...
insert_id = "3000"
update_comment_str = "example"
#query
post_obj = Post.objects(_id=str(_id)).first()
#find the element's position and update
position = 0
for position,_ in enumerate(post_obj.comments):
if post_obj.comments[position].comment_id = insert_id:
break;
post_obj.comments.insert(position+1,Comment(comment_id=str(len(post_obj.comments)+1),comment=update_comment_str)
#save
post_obj.save()
速度很慢,因为我将整个文档提取到python实例中。然后我保存了文档。如何对其进行优化?
答案 0 :(得分:1)
我相信您可以使用mongoengine的push运算符来做到这一点。 例如:
post = Post(comments=[Comment(comment='a'), Comment('c')]).save()
Post.objects(id=post.id).update(push__comments__1=[Comment(comment='b')])
Post.objects.as_pymongo() # [{u'_id': ObjectId('5cd49aa24ec5dc4cd7f5bbc8'), u'comments': [{u'comment': u'a'}, {u'comment': u'b'}, {u'comment': u'c'}]}]
如果您不知道位置,则可以使用汇总查询先找到该位置:
# Find position
projection = {"index": { "$indexOfArray": [ "$comments.comment", 'c' ] }}
data = list(Post.objects(id=post.id).aggregate(
{'$project': projection}))
position = data[0]['index']
# Push at position
key = "push__comments__{}".format(position)
Post.objects(id=post.id).update(**{key: [Comment(comment='b')]})
答案 1 :(得分:0)
在PyMongo中,有一种名为bulk_write
的方法可以
呼叫更新/插入/删除操作(http://api.mongodb.com/python/current/examples/bulk.html)。不幸的是,MongoEngine不支持它。但仍然可以将pymongo和MongoEngine结合使用。