Search code examples
mongodbcursor

Cursor isolation in mongoDB


First of all please forgive me for asking a silly question but I am new to mongodb and learning about cursors. I have a question that why we need cursor isolation?.The manual says "intervening write operations on a document may result in a cursor that returns a document more than once if that document has changed. ". I am not able to understand this. I would be glad if someone can throw more light on it or give some example.


Solution

  • Ok basically MongoDB reads directly form the data files in batches of 100 (can be changed with batch_size to max of 16MB, basically the return is a single BSON document).

    This is in contrast to SQL which writes out a static result set. So immediately you understand that cursors, if they have operations interleave with them can return documents if they change in the sort, i.e. if you have this query:

    db.c.find().sort({s:1});
    

    Where s is an integer, whereby you modify the first document found to have the highest s so that it appears at the back you can actually (by the last batch) get that document again.

    This is, of course, a huge problem. You can end up going round in circles in some cases never finishing a query.

    Normally this isn't possible using the I in ACID but then you must understand that MongoDB doesn't like ACID and doesn't follow it ( http://docs.mongodb.org/manual/faq/concurrency/ ) and uses specific concurrency rules that actually break cursor isolation in such a way that the write operation to update the s of the document does occur before you exhaust the cursor even if it happens in another thread.

    Hopefully that has cleared it up for you.