MongoEngine/mongoengine — pull request #511 by FrankSomething (2013-11-12 21:12:48+00:00)
Title: Conditional save for atomic-style operations

Software often requires an atomic-style database read-and-modify, i.e.:

1. read a record from the database into memory
2. modify the record in some way
3. store the modified record in the database

in a way that ensures no other changes to the database record have occurred between steps 1 and 3. A simple example of this pattern is document versioning. E.g.:

1. read version (n) of a document from the database
2. modify the document, creating version (n+1)
3. store version (n+1) in the database

If two users (e.g., user A and user B) attempt to perform this type of operation at the same time, it it uncertain which new version of the document will be stored in the database, but the other can be lost irrevocably. Furthermore, depending on the nature of the updates (e.g., if the updates are expressed as "deltas" between documents), this situation can result in invalid documents being stored in the database.

Mongo's `collection.update` method includes a `query` document and an `update` document that allows a user to prevent the aforementioned. Continuing with the versioning example, a client can include the expected version number in the `query` document. E.g.:
```
db.collection.update(
{_id:document_id, version:n},
{$set:
{version: (n+1)}})`; if the document version stored in the database does not match, the database document is not altered.