Search code examples
mongodblockingatomicfindandmodify

Mongodb findAndModify atomicity


I want to know how to reference the returned document attributes from find and use it within modify. E.x. :

var totalNoOfSubjects = 5;
db.people.findAndModify( {
    query: { name: "Tom", state: "active", rating: { $gt: 10 } },
    sort: { rating: 1 },
    update: { $set: { average: <reference score value returned by find>/totalNoOfSubjects} }
    } );

My understanding is that findAndModify locks the document, hence I want to perform the update in the modify using the attributes found in the find. This will make the operation atomic.

I am wondering if this is supported by mongo.


Solution

  • No, you cannot refer to values in the found document during the update portion of a findAndModify. It's the same as update in this respect.

    As such, you cannot do this atomically as you need to first fetch the document and then craft the update or findAndMondify to contain the value computed from your fetched doc.

    See https://jira.mongodb.org/browse/SERVER-458 for one way this may be addressed in the future.