4

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.

Raghu Katti
  • 63
  • 1
  • 5

2 Answers2

1

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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • appreciate the reply... I wish Mongo supported this feature although I cannot think of reason that would prevent from supporting it. If $inc can atomically modify using the returned document in the find portion although done by mongo internally...then similarly why not let user also specify references to values returned from find in the update portion... thanks again – Raghu Katti Feb 12 '13 at 09:37
-1

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.

Sri Sankaran
  • 8,120
  • 4
  • 38
  • 47
  • On the contrary, the "find" and "update" parts of the command is not atomic. Other operations can be executed in between the find and update. This is why it cannot be used to enforce uniqueness on a field and you'll need a unique constraint. Ref: https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/#upsert-and-unique-index – Iravanchi Jul 16 '17 at 13:31
  • @Iravanchi: Per the link you have referenced "When modifying a _single document_, both ```findAndModify()``` and the ```update()``` method _atomically_ update the document." – Sri Sankaran Jul 17 '17 at 14:53