Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialization "isolation level" in MongoDB, or the lost-update problem

I realize MongoDB is a NoSQL solution, but I was wondering if it had some sort of equivalent to serialization-level transaction isolation level.

If not, how would you solve the lost-update problem in MongoDB?

I want to keep the revision history of some data in Mongo and each revision has to point to the one before it. How can I make sure no more than one latest revision exists for my data, and on the other hand that no revision is lost due to concurrent updates?

** Edit **

Oops, RTFM, it is indeed possible: http://www.mongodb.org/display/DOCS/Atomic+Operations

Not sure if I should close the question since the knowledge might be relevant to other people..

like image 616
Assaf Lavie Avatar asked May 20 '11 15:05

Assaf Lavie


People also ask

What is serialization isolation?

Serializable isolation preserves the illusion that a transaction running against a table is the only transaction that is running against that table. For example, two concurrently running transactions, T1 and T2, must produce the same results as at least one of the following: T1 and T2 run serially in that order.

Does MongoDB provide isolation?

MongoDB includes a number of features that allow database administrators and developers to isolate workload by functional or geographical groupings.

Which is the most restrictive isolation level in transaction?

Repeatable Read – This is the most restrictive isolation level. The transaction holds read locks on all rows it references and writes locks on referenced rows for update and delete actions. Since other transactions cannot read, update or delete these rows, consequently it avoids non-repeatable read.

How consistency is maintained in MongoDB?

By default, MongoDB is a strongly consistent system. Once a write completes, any subsequent read will return the most recent value. Cassandra, by default, is an eventually consistent system. Once a write completes, the latest data eventually becomes available provided no subsequent changes are made.


1 Answers

Yes, this is possible, so long as you keep the history in a single document. MongoDB supports atomic updates within the scope of a document, but not across multiple documents in a collection.

So, you could embed the history in an array, using a schema something like this:

{
    _id: 12345,
    value: "Apple",
    history:
    [
        { revisionid: 2, value: "Orange" },
        { revisionid: 1, value: "Pear" }
    ]
}

For example, you could insert a new document:

db.things.insert( { _id: 123, value: "Apple" } )

Then update it in one atomic operation:

db.things.update( { _id: 123 },
    {
        $set: { value: "Orange" },
        $push : { history : { revisionid: 1, value: "Apple" } }
    }
)
like image 174
Chris Fulstow Avatar answered Oct 13 '22 22:10

Chris Fulstow