Class: Mongo::Grid::FSBucket

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/mongo/grid/fs_bucket.rb,
lib/mongo/grid/stream.rb,
lib/mongo/grid/stream/read.rb,
lib/mongo/grid/stream/write.rb

Overview

Represents a view of the GridFS in the database.

Since:

  • 2.0.0

Defined Under Namespace

Modules: Stream

Constant Summary

DEFAULT_ROOT =

The default root prefix.

Since:

  • 2.0.0

'fs'.freeze
CHUNKS_INDEX =

The specification for the chunks collection index.

Since:

  • 2.0.0

{ :files_id => 1, :n => 1 }.freeze
FILES_INDEX =

The specification for the files collection index.

Since:

  • 2.1.0

{ filename: 1, uploadDate: 1 }.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(database, options = {}) ⇒ FSBucket

Create the GridFS.

Examples:

Create the GridFS.

Grid::FSBucket.new(database)

Parameters:

  • database (Database)

    The database the files reside in.

  • options (Hash) (defaults to: {})

    The GridFS options.

Options Hash (options):

  • :fs_name (String)

    The prefix for the files and chunks collections.

  • :bucket_name (String)

    The prefix for the files and chunks collections.

  • :chunk_size (Integer)

    Override the default chunk size.

  • :write (String)

    The write concern.

  • :read (String)

    The read preference.

Since:

  • 2.0.0



151
152
153
154
155
156
# File 'lib/mongo/grid/fs_bucket.rb', line 151

def initialize(database, options = {})
  @database = database
  @options = options
  @chunks_collection = database[chunks_name]
  @files_collection = database[files_name]
end

Instance Attribute Details

#chunks_collectionCollection (readonly)

Returns chunks_collection The chunks collection.

Returns:

  • (Collection)

    chunks_collection The chunks collection.

Since:

  • 2.0.0



42
43
44
# File 'lib/mongo/grid/fs_bucket.rb', line 42

def chunks_collection
  @chunks_collection
end

#databaseDatabase (readonly)

Returns database The database.

Returns:

Since:

  • 2.0.0



47
48
49
# File 'lib/mongo/grid/fs_bucket.rb', line 47

def database
  @database
end

#files_collectionCollection (readonly)

Returns files_collection The files collection.

Returns:

  • (Collection)

    files_collection The files collection.

Since:

  • 2.0.0



52
53
54
# File 'lib/mongo/grid/fs_bucket.rb', line 52

def files_collection
  @files_collection
end

#optionsHash (readonly)

Returns options The FSBucket options.

Returns:

  • (Hash)

    options The FSBucket options.

Since:

  • 2.1.0



57
58
59
# File 'lib/mongo/grid/fs_bucket.rb', line 57

def options
  @options
end

Instance Method Details

#delete(id) ⇒ Result

Remove a single file, identified by its id from the GridFS.

Examples:

Remove a file from the GridFS.

fs.delete(id)

Parameters:

  • id (BSON::ObjectId, Object)

    The id of the file to remove.

Returns:

  • (Result)

    The result of the remove.

Raises:

Since:

  • 2.1.0



196
197
198
199
200
201
# File 'lib/mongo/grid/fs_bucket.rb', line 196

def delete(id)
  result = files_collection.find(:_id => id).delete_one
  chunks_collection.find(:files_id => id).delete_many
  raise Error::FileNotFound.new(id, :id) if result.n == 0
  result
end

#delete_one(file) ⇒ Result

Remove a single file from the GridFS.

Examples:

Remove a file from the GridFS.

fs.delete_one(file)

Parameters:

Returns:

  • (Result)

    The result of the remove.

Since:

  • 2.0.0



180
181
182
# File 'lib/mongo/grid/fs_bucket.rb', line 180

def delete_one(file)
  delete(file.id)
end

#download_to_stream(id, io) ⇒ Object

Downloads the contents of the file specified by id and writes them to the destination io object.

Examples:

Download the file and write it to the io object.

fs.download_to_stream(id, io)

Parameters:

  • id (BSON::ObjectId, Object)

    The id of the file to read.

  • io (IO)

    The io object to write to.

Since:

  • 2.1.0



234
235
236
237
238
239
240
# File 'lib/mongo/grid/fs_bucket.rb', line 234

def download_to_stream(id, io)
  open_download_stream(id) do |stream|
    stream.each do |chunk|
      io << chunk
    end
  end
end

#download_to_stream_by_name(filename, io, opts = {}) ⇒ Object

Downloads the contents of the stored file specified by filename and by the revision in options and writes the contents to the destination io object.

Revision numbers are defined as follows: 0 = the original stored file 1 = the first revision 2 = the second revision etc… -2 = the second most recent revision -1 = the most recent revision

# @example Download the original file.

fs.download_to_stream_by_name('some-file.txt', io, revision: 0)

Examples:

Download the most recent revision.

fs.download_to_stream_by_name('some-file.txt', io)

Download the second revision of the stored file.

fs.download_to_stream_by_name('some-file.txt', io, revision: 2)

Parameters:

  • filename (String)

    The file's name.

  • io (IO)

    The io object to write to.

  • opts (Hash) (defaults to: {})

    Options for the download.

Options Hash (opts):

  • :revision (Integer)

    The revision number of the file to download. Defaults to -1, the most recent version.

Raises:

Since:

  • 2.1.0



328
329
330
# File 'lib/mongo/grid/fs_bucket.rb', line 328

def download_to_stream_by_name(filename, io, opts = {})
  download_to_stream(open_download_stream_by_name(filename, opts).file_id, io)
end

#find(selector = nil, options = {}) ⇒ CollectionView

Find files collection documents matching a given selector.

Examples:

Find files collection documents by a filename.

fs.find(filename: 'file.txt')

Parameters:

  • selector (Hash) (defaults to: nil)

    The selector to use in the find.

  • options (Hash) (defaults to: {})

    The options for the find.

Options Hash (options):

  • :batch_size (Integer)

    The number of documents returned in each batch of results from MongoDB.

  • :limit (Integer)

    The max number of docs to return from the query.

  • :no_cursor_timeout (true, false)

    The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that.

  • :skip (Integer)

    The number of docs to skip before returning results.

  • :sort (Hash)

    The key and direction pairs by which the result set will be sorted.

Returns:

  • (CollectionView)

    The collection view.

Since:

  • 2.1.0



86
87
88
# File 'lib/mongo/grid/fs_bucket.rb', line 86

def find(selector = nil, options = {})
  files_collection.find(selector, options.merge(read: read_preference))
end

#find_one(selector = nil) ⇒ Grid::File

Deprecated.

Please use #find instead with a limit of -1. Will be removed in version 3.0.

Find a file in the GridFS.

Examples:

Find a file by its id.

fs.find_one(_id: id)

Find a file by its filename.

fs.find_one(filename: 'test.txt')

Parameters:

  • selector (Hash) (defaults to: nil)

    The selector.

Returns:

Since:

  • 2.0.0



106
107
108
109
110
111
# File 'lib/mongo/grid/fs_bucket.rb', line 106

def find_one(selector = nil)
  file_info = files_collection.find(selector).first
  return nil unless file_info
  chunks = chunks_collection.find(:files_id => file_info[:_id]).sort(:n => 1)
  Grid::File.new(chunks.to_a, Options::Mapper.transform(file_info, Grid::File::Info::MAPPINGS.invert))
end

#insert_one(file) ⇒ BSON::ObjectId

Deprecated.

Please use #upload_from_stream or #open_upload_stream instead. Will be removed in version 3.0.

Insert a single file into the GridFS.

Examples:

Insert a single file.

fs.insert_one(file)

Parameters:

Returns:

  • (BSON::ObjectId)

    The file id.

Since:

  • 2.0.0



126
127
128
129
130
131
# File 'lib/mongo/grid/fs_bucket.rb', line 126

def insert_one(file)
  @indexes ||= ensure_indexes!
  chunks_collection.insert_many(file.chunks)
  files_collection.insert_one(file.info)
  file.id
end

#open_download_stream(id) {|The| ... } ⇒ Stream::Read

Opens a stream from which a file can be downloaded, specified by id.

Examples:

Open a stream from which a file can be downloaded.

fs.open_download_stream(id)

Parameters:

  • id (BSON::ObjectId, Object)

    The id of the file to read.

Yield Parameters:

  • The (Hash)

    read stream.

Returns:

Since:

  • 2.1.0



215
216
217
218
219
220
221
222
# File 'lib/mongo/grid/fs_bucket.rb', line 215

def open_download_stream(id)
  read_stream(id).tap do |stream|
    if block_given?
      yield stream
      stream.close
    end
  end
end

#open_download_stream_by_name(filename, opts = {}) {|The| ... } ⇒ Stream::Read

Opens a stream from which the application can read the contents of the stored file specified by filename and the revision in options.

Revision numbers are defined as follows: 0 = the original stored file 1 = the first revision 2 = the second revision etc… -2 = the second most recent revision -1 = the most recent revision

# @example Open a stream to download the original file.

fs.open_download_stream_by_name('some-file.txt', revision: 0)

Examples:

Open a stream to download the most recent revision.

fs.open_download_stream_by_name('some-file.txt')

Open a stream to download the second revision of the stored file.

fs.open_download_stream_by_name('some-file.txt', revision: 2)

Parameters:

  • filename (String)

    The file's name.

  • opts (Hash) (defaults to: {})

    Options for the download.

Options Hash (opts):

  • :revision (Integer)

    The revision number of the file to download. Defaults to -1, the most recent version.

Yield Parameters:

  • The (Hash)

    read stream.

Returns:

Raises:

Since:

  • 2.1.0



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/mongo/grid/fs_bucket.rb', line 276

def open_download_stream_by_name(filename, opts = {}, &block)
  revision = opts.fetch(:revision, -1)
  if revision < 0
    skip = revision.abs - 1
    sort = { 'uploadDate' => Mongo::Index::DESCENDING }
  else
    skip = revision
    sort = { 'uploadDate' => Mongo::Index::ASCENDING }
  end
  file_doc = files_collection.find({ filename: filename} ,
                                     projection: { _id: 1 },
                                     sort: sort,
                                     skip: skip,
                                     limit: -1).first
  unless file_doc
    raise Error::FileNotFound.new(filename, :filename) unless opts[:revision]
    raise Error::InvalidFileRevision.new(filename, opts[:revision])
  end
  open_download_stream(file_doc[:_id], &block)
end

#open_upload_stream(filename, opts = {}) {|The| ... } ⇒ Stream::Write

Opens an upload stream to GridFS to which the contents of a user file came be written.

Examples:

Open a stream to which the contents of a file came be written.

fs.open_upload_stream('a-file.txt')

Parameters:

  • filename (String)

    The filename of the file to upload.

  • opts (Hash) (defaults to: {})

    The options for the write stream.

Options Hash (opts):

  • :file_id (Object)

    An optional unique file id. An ObjectId is generated otherwise.

  • :chunk_size (Integer)

    Override the default chunk size.

  • :write (Hash)

    The write concern.

  • :metadata (Hash)

    User data for the 'metadata' field of the files collection document.

  • :content_type (String)

    The content type of the file. Deprecated, please use the metadata document instead.

  • :aliases (Array<String>)

    A list of aliases. Deprecated, please use the metadata document instead.

Yield Parameters:

  • The (Hash)

    write stream.

Returns:

Since:

  • 2.1.0



355
356
357
358
359
360
361
362
# File 'lib/mongo/grid/fs_bucket.rb', line 355

def open_upload_stream(filename, opts = {})
  write_stream(filename, opts).tap do |stream|
    if block_given?
      yield stream
      stream.close
    end
  end
end

#prefixString

Get the prefix for the GridFS

Examples:

Get the prefix.

fs.prefix

Returns:

  • (String)

    The GridFS prefix.

Since:

  • 2.0.0



166
167
168
# File 'lib/mongo/grid/fs_bucket.rb', line 166

def prefix
  @options[:fs_name] || @options[:bucket_name]|| DEFAULT_ROOT
end

#read_preferenceMongo::ServerSelector

Get the read preference.

Examples:

Get the read preference.

fs.read_preference

Returns:

Since:

  • 2.1.0



411
412
413
# File 'lib/mongo/grid/fs_bucket.rb', line 411

def read_preference
  @read_preference ||= ServerSelector.get(@options[:read] || database.read_preference)
end

#upload_from_stream(filename, io, opts = {}) ⇒ BSON::ObjectId

Uploads a user file to a GridFS bucket. Reads the contents of the user file from the source stream and uploads it as chunks in the chunks collection. After all the chunks have been uploaded, it creates a files collection document for the filename in the files collection.

Examples:

Upload a file to the GridFS bucket.

fs.upload_from_stream('a-file.txt', file)

Parameters:

  • filename (String)

    The filename of the file to upload.

  • io (IO)

    The source io stream to upload from.

  • opts (Hash) (defaults to: {})

    The options for the write stream.

Options Hash (opts):

  • :file_id (Object)

    An optional unique file id. An ObjectId is generated otherwise.

  • :chunk_size (Integer)

    Override the default chunk size.

  • :write (Hash)

    The write concern.

  • :metadata (Hash)

    User data for the 'metadata' field of the files collection document.

  • :content_type (String)

    The content type of the file. Deprecated, please use the metadata document instead.

  • :aliases (Array<String>)

    A list of aliases. Deprecated, please use the metadata document instead.

Returns:

  • (BSON::ObjectId)

    The ObjectId file id.

Since:

  • 2.1.0



389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/mongo/grid/fs_bucket.rb', line 389

def upload_from_stream(filename, io, opts = {})
  open_upload_stream(filename, opts) do |stream|
    begin
      stream.write(io)
    rescue IOError
      begin
        stream.abort
      rescue Error::OperationFailure
      end
      raise
    end
  end.file_id
end

#write_concernMongo::WriteConcern

Get the write concern.

Examples:

Get the write concern.

stream.write_concern

Returns:

Since:

  • 2.1.0



423
424
425
426
# File 'lib/mongo/grid/fs_bucket.rb', line 423

def write_concern
  @write_concern ||= @options[:write] ? WriteConcern.get(@options[:write]) :
      database.write_concern
end