Mongoengine 简明教程

MongoEngine - Atomic Updates

原子性是 ACID 事务属性之一。数据库事务必须是不可分割和不可简化的,以便要么完全发生,要么根本不发生。此属性称为原子性。MongoDB 仅对单一文档支持原子性,而不是多文档事务。

Atomicity is one of the ACID transaction properties. A database transaction has to be indivisible and irreducible so that it either occurs completely or doesn’t occur at all. This property is called Atomicity. MongoDB supports Atomicity only on single documents and not on multi-document transactions.

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

MongoEngine provides the following methods for atomic updates on a queryset.

update_one() - 覆盖或添加与查询匹配的第一条文档。

update_one() − Overwrites or adds first document matched by query.

update() - 对与查询匹配的字段执行原子更新。

update() − Performs atomic update on fields matched by query.

modify() - 更新文档并将其返回。

modify() − Update a document and return it.

以下的修改器可能会与这些方法一起使用。(这些修改器在字段之前,而不是之后)。

Following modifiers may be used with these methods. (These modifiers come before the field, not after).

set

set a particular value

unset

delete a particular value

inc

increment a value by a given amount

dec

decrement a value by a given amount

push

append a value to a list

push_all

append several values to a list

pop

remove the first or last element of a list depending on the value

pull

remove a value from a list

pull_all

remove several values from a list

add_to_set

add value to a list only if its not in the list already

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

The following is an example of atomic update, we first create a Document class called tests and add a document in it.

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() 方法将 name 字段从 XYZ 更新为 MongoDB。

Let us use update_one() method to update name field from XYZ to MongoDB.

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

push 修改器用于在 ListField(scores)中添加数据。

The push modifier is used to add data in ListField (scores).

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

若要将 attempts 字段增加 1,我们可以使用 inc 修改器。

To increment attempts field by one, we can use inc modifier.

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

更新后的文档如下所示 -

The updated document looks as follows −

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