GridFS and Ruby
If want to find all GridFS files that are stored in a database, you can query the system table that holds this information. GridFS uses two system tables, one for holding the filenames and another that holds the actual binary data of a chunk .( There’ s an example screens ho to np 86.) The default behaviour of GridFS is to use two collections with names prefixed by fs bucket:
fs.chunks and fs.files. The following Ruby code inserts both a existing binary file and a text file that’s created on the fly as GridFS objects: fs=$client.d at abase.fs $file= File. open (" i ma ge.png ") $fi le_ id=fs. upload_ from_ stream (" i ma ge.png ”, $file) $file.close # To create a file with raw data and insert it file= Mon go :: Grid :: File. new (' I am a NEW file stored in GridFS’, :filename => ‘aFile.txt') $client.d at abase.fs. insert_ one( file) You should look at storeGridFS.rb on the
LXFDVD for the complete source code. The next section of Ruby code, which can be found in
retrieve Grid F S. rb, retrieves a previously inserted GridFS file using its file_id: # Upload a text file fs=$client.d at abase.fs $file= File. open (" connect. rb ") $fi le_ id=fs. upload_ from_ stream (" connect. rb ”, $file) $file.close # Download a file $file_ to_ write= File. open (' perfect Copy’ ,‘w ')
fs. download_ to_ stream ($ file_ id ,$ file_ to_ write)
As you can see from the Ruby code ( above), the new copy of the GridFS file will be named
perfect Copy .( The screens ho to np 87 shows both Ruby examples, storeGridFS.rb and
retrieve Grid F S. rb in action ). Please note that the first program ( storeGridFS.rb) blindly inserts two files, therefore if you run it multiple times, both files will be inserted multiple times ( asyoucanseein the screenshot on p87). You can only differentiate between the various copies of the same GridFS file using the _id field.
You will discover that the MongoDB documentation that shows how to use the Ruby driver to retrieve GridFS files from a MongoDB database is a little unclear, but you’ll find that
retrieve Grid F S. rb is better.