tags:

views:

40

answers:

1

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]
+2  A: 

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.

Cameron
It is a bit convoluted but it works! Thanks!
Matt Taylor