MongoEngine – Atomic Updates
”;
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 provides the following methods for atomic updates on a queryset.
update_one() − Overwrites or adds first document matched by query.
update() − Performs atomic update on fields matched by query.
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()
Let us use update_one() method to update name field from XYZ to MongoDB.
tests.objects(name=''XYZ'').update_one(set__name=''MongoDB'')
The push modifier is used to add data in ListField (scores).
tests.objects(name=''MongoDB'').update_one(push__scores=50)
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"}] }
”;