Question

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.

Was it helpful?

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.

OTHER TIPS

Atomicity is exactly the reason for findAndModify.

As stated in the docs, Mongo will find one or more documents (matching the query specified) modify one document (using the update specified). The whole process is atomic. Default implementation has Mongo returning the found document (in its unchanged state). This can be modified using the new option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top