Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo shell cursor: updated documents get to cursor again

I am trying to iterate through cursor in Mongo shell to update all documents in collection.

My aim was to rename some fields in documents, so the code looked something like this:

var cursor = db.collection.find();

while ( cursor.hasNext() )
{
    var doc = cursor.next();

    printjson(doc);

    db.collection.update(   { _id : doc._id },
                            {   $set : {    docId : doc.docID,
                                            createdAt : doc.dateAdded,
                                            updatedAt : doc.dateAdded },
                                $unset : {  dateAdded : "",
                                            docID : "" } }
                        );
}

The code is extremely simple, so I was very surprised when in some updated documents the fields docId, createdAt and updatedAt were set to null, although before that update these fields had reasonable values.

After some debug actions and adding printjson to code it turned out that the loop at first iterated through all the documents in collection, but then it did not stop iterating and continued looping through already updated documents one more time. By the way, the number of documents in cursor does not change according to cursor.count().

I am trying to find out if this behaviour of cursor is a bug or some strange feature. I am using Ubuntu 12.10 and Mongo 2.4.6.

Thank you in advance.

PS Yes, I know about $rename tag. But I will encounter the same problem when trying to set the field updatedAt if dateAdded does not exist anymore in already updated document. And this does not reject the fact of the strange cursor behaviour.

like image 367
strelga Avatar asked Jan 20 '26 01:01

strelga


1 Answers

It's a feature of MongoDb that the cursor may reflect changes that have been made earlier. A cursor is not isolated. You'll need to modify your loop to handle this feature.

Cursor Isolation Because the cursor is not isolated during its lifetime, intervening write operations on a document may result in a cursor that returns a document more than once if that document has changed. To handle this situation, see the information on snapshot mode.

Reference.

like image 111
WiredPrairie Avatar answered Jan 22 '26 14:01

WiredPrairie