Find and Modify (or Remove)
MongoDB 1.3+ supports a "find, modify, and return" command. This command can be used to atomically modify a document (at most one) and return it. Note that, by default, the document returned will not include the modifications made on the update.
The general form is db.runCommand( { findandmodify : <collection>,
<options> } )
The MongoDB shell includes a helper method, findAndModify(), for executing the command. Some drivers provide helpers also. At least one of the update or remove parameters is required; the other arguments are optional.
The sort option is useful when storing queue-like data. Let's take the example of fetching the highest priority job that hasn't been grabbed yet and atomically marking it as grabbed: job = db.jobs.findAndModify({
query: {inprogress:false},
sort:{priority:-1},
update: {$set: {inprogress: true, started: new Date()}}
});
You could also simply remove the object to be returned, but be careful. If the client crashes before processing the job, the document will be lost forever. job = db.jobs.findAndModify({sort:{priority:-1}, remove:true}}});
See the tests for more examples. If your driver doesn't provide a helper function for this command, run the command directly with something like this: job = db.runCommand({ findandmodify : "jobs",
sort : { priority : -1 },
remove : true
}).value;
Sharding limitationsfindandmodify will behave the same when called through a mongos as long as the collection it is modifying is unsharded. If the collection is sharded, then the query must contain the shard key. This is the same as regular sharded updates. See Also |

PLEASE POST QUESTIONS IN THE USER GROUPS FORUM. Post non-question comments and helpful hints here.
blog comments powered by Disqus