views:

35

answers:

2

Does GridFS have an upsert?

For example, if i want to save an image with a specified _id, and one with that same _id already exists, i want it to overwrite (update) it. Otherwise, insert it.

Thanks!

Matt

A: 

I looked at the mongo ruby gem source code and found this:

# Store a file in the file store. This method is designed only for writing new files;
# if you need to update a given file, first delete it using #Grid#delete.
# ...
def put(data, opts={})

So, I did this in the code:

grid.delete(id) # if exists  
grid.put(tmp_file.read, :_id => id, :content_type => file_type)

See the working sinatra script here: http://github.com/acani/acani-sinatra/blob/master/acani.rb#L97

MattDiPasquale
A: 

The spec isn't really designed to support upserts, since you're technically modifying more than one document, and certainly tricky race conditions can arise. So we recommend what Matt has done, which is to delete first and then put.

Kyle Banker