Reputation: 1349
I want to add a element in a ListField.Here is my code:
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()
It's slow because I fetch the whole document into python instance .Then I save document.How to optimize it?
Upvotes: 0
Views: 1185
Reputation: 6374
I believe you can do this with the push operator of mongoengine. e.g:
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'}]}]
If you don't know the position in advance, you can use an aggregate query to find it first:
# 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')]})
Upvotes: 2
Reputation: 597
in PyMongo, there is method called bulk_write
to
call update/insert/delete operations (http://api.mongodb.com/python/current/examples/bulk.html). Unfortunately, it is not supported in MongoEngine. But still, you can combine pymongo and MongoEngine.
Upvotes: 0