如何在 python 中使用 mongoengine 在 ListField 中的元素后插入?

How to insert after a element in a ListField with mongoengine in python?

我想在ListField.Here中添加一个元素,我的代码是:

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 实例中。然后我保存 document.How 以优化它?

在 PyMongo 中,有一个名为 bulk_write 的方法来 调用 update/insert/delete 操作 (http://api.mongodb.com/python/current/examples/bulk.html)。不幸的是,MongoEngine 不支持它。但是,您仍然可以结合使用 pymongo 和 MongoEngine。

我相信你可以用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')]})