MongoEngine 原子更新


原子性是 ACID 事务属性之一。数据库事务必须是不可分割和不可约的,这样它要么完全发生,要么根本不发生。此属性称为原子性。 MongoDB 仅在单个文档上支持原子性,而不在多文档事务上支持。

MongoEngine 为查询集上的原子更新提供了以下方法。

update_one() :覆盖或添加查询匹配的第一个文档。

update() :对查询匹配的字段进行原子更新。

modify() : 更新一个文档并返回。

以下修饰符可以与这些方法一起使用。 (这些修饰符出现在字段之前,而不是之后)。

set 设置特定值
unset 删除特定值
inc 将值增加给定的数量
dec 将值递减给定数量
push 将值附加到列表
push_all 将多个值附加到列表
pop 根据值删除列表的第一个或最后一个元素
pull 从列表中删除一个值
pull_all 从列表中删除多个值
add_to_set 仅当它不在列表中时才向列表添加值

下面是一个原子更新的例子,我们首先创建一个名为 tests 的 Document 类,并在其中添加一个文档。

from mongoengine import *
con=connect('newdb')

class tests (Document):
    name=StringField()
    attempts=IntField()
    scores=ListField(IntField())

t1=tests()
t1.name='XYZ'
t1.attempts=0
t1.scores=[]
t1.save()

让我们使用 update_one() 将名称字段从 XYZ 更新到 MongoDB 的方法。

tests.objects(name='XYZ').update_one(set__name='MongoDB')

push 修饰符用于在 ListField 中添加数据(分数)。

tests.objects(name='MongoDB').update_one(push__scores=50)

要将尝试字段加一,我们可以使用 inc 修饰符。

tests.objects(name='MongoDB').update_one(inc__attempts=1)

更新后的文档如下:

{
"_id":{"$oid":"5ebcf8d353a48858e01ced04"},
"name":"MongoDB",
"attempts":{"$numberInt":"1"},
"scores":[{"$numberInt":"50"}]
}