How do I implement an atomic stack with mongoDB and Ruby
I want to push and pull things off of a stack in an atomic way using ruby and mongoDB.
The push I can do atomically via the following code example:
collection.update({"_id" => document["_id"]}, {"$push" => {field_name => value}})
Example code for pop:
value = collection.update({"_id" => document["_id"]}, {"$pop" => {field_name => -1}})
开发者_运维技巧
Unfortunately the value returned above is not the value that was 'popped' off the stack.
It seems like a very useful function/feature, and I find it hard to believe this isn't possible with mongoDB.
Update
For the benefit of those looking for the complete answer, here it is (Thanks again Cameron):
result = collection.find_and_modify({:query => {"_id" => document["_id"]}, :update => {"$pop" => {field_name => -1}}})
return result[field_name][0]
Looks like you want the findandmodify
command. This command allows you to modify a document atomically and return the document that was modified. Note that by default, the document returned is the version before it was modified. In this case, that is exactly what you want, since you can then get the last item in the stack yourself.
Unfortunately I don't know the Ruby driver, but the documentation should point you in the right direction syntax-wise.
精彩评论