Module: Mongo::Collection::View::Readable

Included in:
Mongo::Collection::View
Defined in:
lib/mongo/collection/view/readable.rb

Overview

Defines read related behavior for collection view.

Since:

  • 2.0.0

Instance Method Summary collapse

Instance Method Details

#aggregate(pipeline, options = {}) ⇒ Aggregation

Execute an aggregation on the collection view.

Examples:

Aggregate documents.

view.aggregate([
  { "$group" => { "_id" => "$city", "tpop" => { "$sum" => "$pop" }}}
])

Parameters:

  • pipeline (Array<Hash>)

    The aggregation pipeline.

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

    The aggregation options.

Options Hash (options):

  • :allow_disk_use (true, false)

    Set to true if disk usage is allowed during the aggregation.

  • :batch_size (Integer)

    The number of documents to return per batch.

  • :bypass_document_validation (true, false)

    Whether or not to skip document level validation.

  • :collation (Hash)

    The collation to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :hint (String)

    The index to use for the aggregation.

  • :let (Hash)

    Mapping of variables to use in the pipeline. See the server documentation for details.

  • :max_time_ms (Integer)

    The maximum amount of time in milliseconds to allow the aggregation to run.

  • :use_cursor (true, false)

    Indicates whether the command will request that the server provide results using a cursor. Note that as of server version 3.6, aggregations always provide results using a cursor and this option is therefore not valid.

  • :session (Session)

    The session to use.

Returns:

Since:

  • 2.0.0



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mongo/collection/view/readable.rb', line 60

def aggregate(pipeline, options = {})
  options = @options.merge(options) unless Mongo.broken_view_options
  aggregation = Aggregation.new(self, pipeline, options)

  # Because the $merge and $out pipeline stages write documents to the
  # collection, it is necessary to clear the cache when they are performed.
  #
  # Opt to clear the entire cache rather than one namespace because
  # the $out and $merge stages do not have to write to the same namespace
  # on which the aggregation is performed.
  QueryCache.clear if aggregation.write?

  aggregation
end

#allow_disk_useView

Allows the server to write temporary data to disk while executing a find operation.

Returns:

  • (View)

    The new view.

Since:

  • 2.0.0



79
80
81
# File 'lib/mongo/collection/view/readable.rb', line 79

def allow_disk_use
  configure(:allow_disk_use, true)
end

#allow_partial_resultsView

Allows the query to get partial results if some shards are down.

Examples:

Allow partial results.

view.allow_partial_results

Returns:

  • (View)

    The new view.

Since:

  • 2.0.0



91
92
93
# File 'lib/mongo/collection/view/readable.rb', line 91

def allow_partial_results
  configure(:allow_partial_results, true)
end

#await_dataView

Tell the query’s cursor to stay open and wait for data.

Examples:

Await data on the cursor.

view.await_data

Returns:

  • (View)

    The new view.

Since:

  • 2.0.0



103
104
105
# File 'lib/mongo/collection/view/readable.rb', line 103

def await_data
  configure(:await_data, true)
end

#batch_size(batch_size = nil) ⇒ Integer, View

Note:

Specifying 1 or a negative number is analogous to setting a limit.

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

Examples:

Set the batch size.

view.batch_size(5)

Parameters:

  • batch_size (Integer) (defaults to: nil)

    The size of each batch of results.

Returns:

  • (Integer, View)

    Either the batch_size value or a new View.

Since:

  • 2.0.0



120
121
122
# File 'lib/mongo/collection/view/readable.rb', line 120

def batch_size(batch_size = nil)
  configure(:batch_size, batch_size)
end

#comment(comment = nil) ⇒ String, View

Note:

Set profilingLevel to 2 and the comment will be logged in the profile collection along with the query.

Associate a comment with the query.

Examples:

Add a comment.

view.comment('slow query')

Parameters:

  • comment (Object) (defaults to: nil)

    The comment to be associated with the query.

Returns:

  • (String, View)

    Either the comment or a new View.

Since:

  • 2.0.0



138
139
140
# File 'lib/mongo/collection/view/readable.rb', line 138

def comment(comment = nil)
  configure(:comment, comment)
end

#count(opts = {}) ⇒ Integer

Deprecated.

Use #count_documents or #estimated_document_count instead. However, note that the following operators will need to be substituted when switching to #count_documents:

* $where should be replaced with $expr (only works on 3.6+)
* $near should be replaced with $geoWithin with $center
* $nearSphere should be replaced with $geoWithin with $centerSphere

Get a count of matching documents in the collection.

Examples:

Get the number of documents in the collection.

collection_view.count

Parameters:

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

    Options for the operation.

Options Hash (opts):

  • :skip (Integer)

    The number of documents to skip.

  • :hint (Hash)

    Override default index selection and force MongoDB to use a specific index for the query.

  • :limit (Integer)

    Max number of docs to count.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

  • :session (Mongo::Session)

    The session to use for the operation.

  • :comment (Object)

    A user-provided comment to attach to this command.

Returns:

  • (Integer)

    The document count.

Since:

  • 2.0.0



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/mongo/collection/view/readable.rb', line 170

def count(opts = {})
  opts = @options.merge(opts) unless Mongo.broken_view_options
  cmd = { :count => collection.name, :query => filter }
  cmd[:skip] = opts[:skip] if opts[:skip]
  cmd[:hint] = opts[:hint] if opts[:hint]
  cmd[:limit] = opts[:limit] if opts[:limit]
  if read_concern
    cmd[:readConcern] = Options::Mapper.transform_values_to_strings(
      read_concern)
  end
  cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms]
  Mongo::Lint.validate_underscore_read_preference(opts[:read])
  read_pref = opts[:read] || read_preference
  selector = ServerSelector.get(read_pref || server_selector)
  with_session(opts) do |session|
    read_with_retry(session, selector) do |server|
      Operation::Count.new(
        selector: cmd,
        db_name: database.name,
        options: {:limit => -1},
        read: read_pref,
        session: session,
        # For some reason collation was historically accepted as a
        # string key. Note that this isn't documented as valid usage.
        collation: opts[:collation] || opts['collation'] || collation,
        comment: opts[:comment],
      ).execute(server, context: Operation::Context.new(client: client, session: session))
    end.n.to_i
  end
end

#count_documents(opts = {}) ⇒ Integer

Get a count of matching documents in the collection.

Examples:

Get the number of documents in the collection.

collection_view.count

Parameters:

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

    Options for the operation.

  • ops (Hash)

    a customizable set of options

Options Hash (opts):

  • :skip (Integer)

    The number of documents to skip.

  • :hint (Hash)

    Override default index selection and force MongoDB to use a specific index for the query. Requires server version 3.6+.

  • :limit (Integer)

    Max number of docs to count.

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

  • :session (Mongo::Session)

    The session to use for the operation.

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/mongo/collection/view/readable.rb', line 223

def count_documents(opts = {})
  opts = @options.merge(opts) unless Mongo.broken_view_options
  pipeline = [:'$match' => filter]
  pipeline << { :'$skip' => opts[:skip] } if opts[:skip]
  pipeline << { :'$limit' => opts[:limit] } if opts[:limit]
  pipeline << { :'$group' => { _id: 1, n: { :'$sum' => 1 } } }

  opts = opts.slice(:hint, :max_time_ms, :read, :collation, :session, :comment)
  opts[:collation] ||= collation

  first = aggregate(pipeline, opts).first
  return 0 unless first
  first['n'].to_i
end

#cursor_type(type = nil) ⇒ :tailable, ...

The type of cursor to use. Can be :tailable or :tailable_await.

Examples:

Set the cursor type.

view.cursor_type(:tailable)

Parameters:

  • type (:tailable, :tailable_await) (defaults to: nil)

    The cursor type.

Returns:

  • (:tailable, :tailable_await, View)

    Either the cursor type setting or a new View.

Since:

  • 2.3.0



626
627
628
# File 'lib/mongo/collection/view/readable.rb', line 626

def cursor_type(type = nil)
  configure(:cursor_type, type)
end

#distinct(field_name, opts = {}) ⇒ Array<Object>

Get a list of distinct values for a specific field.

Examples:

Get the distinct values.

collection_view.distinct('name')

Parameters:

  • field_name (String, Symbol)

    The name of the field.

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

    Options for the distinct command.

  • options (Hash)

    a customizable set of options

Options Hash (opts):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :read (Hash)

    The read preference options.

  • :collation (Hash)

    The collation to use.

Returns:

  • (Array<Object>)

    The list of distinct values.

Since:

  • 2.0.0



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/mongo/collection/view/readable.rb', line 317

def distinct(field_name, opts = {})
  if field_name.nil?
    raise ArgumentError, 'Field name for distinct operation must be not nil'
  end
  opts = @options.merge(opts) unless Mongo.broken_view_options
  cmd = { :distinct => collection.name,
          :key => field_name.to_s,
          :query => filter, }
  cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms]
  if read_concern
    cmd[:readConcern] = Options::Mapper.transform_values_to_strings(
      read_concern)
  end
  Mongo::Lint.validate_underscore_read_preference(opts[:read])
  read_pref = opts[:read] || read_preference
  selector = ServerSelector.get(read_pref || server_selector)
  with_session(opts) do |session|
    read_with_retry(session, selector) do |server|
      Operation::Distinct.new(
        selector: cmd,
        db_name: database.name,
        options: {:limit => -1},
        read: read_pref,
        session: session,
        comment: opts[:comment],
        # For some reason collation was historically accepted as a
        # string key. Note that this isn't documented as valid usage.
        collation: opts[:collation] || opts['collation'] || collation,
      ).execute(server, context: Operation::Context.new(client: client, session: session))
    end.first['values']
  end
end

#estimated_document_count(opts = {}) ⇒ Integer

Gets an estimate of the count of documents in a collection using collection metadata.

Examples:

Get the number of documents in the collection.

collection_view.estimated_document_count

Parameters:

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

    Options for the operation.

Options Hash (opts):

  • :max_time_ms (Integer)

    The maximum amount of time to allow the command to run.

  • :read (Hash)

    The read preference options.

  • :comment (Object)

    A user-provided comment to attach to this command.

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/mongo/collection/view/readable.rb', line 254

def estimated_document_count(opts = {})
  unless view.filter.empty?
    raise ArgumentError, "Cannot call estimated_document_count when querying with a filter"
  end

  %i[limit skip].each do |opt|
    if options.key?(opt) || opts.key?(opt)
      raise ArgumentError, "Cannot call estimated_document_count when querying with #{opt}"
    end
  end

  opts = @options.merge(opts) unless Mongo.broken_view_options
  Mongo::Lint.validate_underscore_read_preference(opts[:read])
  read_pref = opts[:read] || read_preference
  selector = ServerSelector.get(read_pref || server_selector)
  with_session(opts) do |session|
    read_with_retry(session, selector) do |server|
      context = Operation::Context.new(client: client, session: session)
      cmd = { count: collection.name }
      cmd[:maxTimeMS] = opts[:max_time_ms] if opts[:max_time_ms]
      if read_concern
        cmd[:readConcern] = Options::Mapper.transform_values_to_strings(read_concern)
      end
      result = Operation::Count.new(
        selector: cmd,
        db_name: database.name,
        read: read_pref,
        session: session,
        comment: opts[:comment],
      ).execute(server, context: context)
      result.n.to_i
    end
  end
rescue Error::OperationFailure => exc
  if exc.code == 26
    # NamespaceNotFound
    # This should only happen with the aggregation pipeline path
    # (server 4.9+). Previous servers should return 0 for nonexistent
    # collections.
    0
  else
    raise
  end
end

#hint(hint = nil) ⇒ Hash, View

The index that MongoDB will be forced to use for the query.

Examples:

Set the index hint.

view.hint(name: 1)

Parameters:

  • hint (Hash) (defaults to: nil)

    The index to use for the query.

Returns:

  • (Hash, View)

    Either the hint or a new View.

Since:

  • 2.0.0



360
361
362
# File 'lib/mongo/collection/view/readable.rb', line 360

def hint(hint = nil)
  configure(:hint, hint)
end

#limit(limit = nil) ⇒ Integer, View

The max number of docs to return from the query.

Examples:

Set the limit.

view.limit(5)

Parameters:

  • limit (Integer) (defaults to: nil)

    The number of docs to return.

Returns:

  • (Integer, View)

    Either the limit or a new View.

Since:

  • 2.0.0



374
375
376
# File 'lib/mongo/collection/view/readable.rb', line 374

def limit(limit = nil)
  configure(:limit, limit)
end

#map_reduce(map, reduce, options = {}) ⇒ MapReduce

Execute a map/reduce operation on the collection view.

Examples:

Execute a map/reduce.

view.map_reduce(map, reduce)

Parameters:

  • map (String)

    The map js function.

  • reduce (String)

    The reduce js function.

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

    The map/reduce options.

Returns:

Since:

  • 2.0.0



390
391
392
# File 'lib/mongo/collection/view/readable.rb', line 390

def map_reduce(map, reduce, options = {})
  MapReduce.new(self, map, reduce, @options.merge(options))
end

#max_await_time_ms(max = nil) ⇒ Integer, View

A cumulative time limit in milliseconds for processing get more operations on a cursor.

Examples:

Set the max await time ms value.

view.max_await_time_ms(500)

Parameters:

  • max (Integer) (defaults to: nil)

    The max time in milliseconds.

Returns:

  • (Integer, View)

    Either the max await time ms value or a new View.

Since:

  • 2.1.0



598
599
600
# File 'lib/mongo/collection/view/readable.rb', line 598

def max_await_time_ms(max = nil)
  configure(:max_await_time_ms, max)
end

#max_scan(value = nil) ⇒ Integer, View

Deprecated.

This option is deprecated as of MongoDB server version 4.0.

Set the max number of documents to scan.

Examples:

Set the max scan value.

view.max_scan(1000)

Parameters:

  • value (Integer) (defaults to: nil)

    The max number to scan.

Returns:

  • (Integer, View)

    The value or a new View.

Since:

  • 2.0.0



407
408
409
# File 'lib/mongo/collection/view/readable.rb', line 407

def max_scan(value = nil)
  configure(:max_scan, value)
end

#max_time_ms(max = nil) ⇒ Integer, View

A cumulative time limit in milliseconds for processing operations on a cursor.

Examples:

Set the max time ms value.

view.max_time_ms(500)

Parameters:

  • max (Integer) (defaults to: nil)

    The max time in milliseconds.

Returns:

  • (Integer, View)

    Either the max time ms value or a new View.

Since:

  • 2.1.0



612
613
614
# File 'lib/mongo/collection/view/readable.rb', line 612

def max_time_ms(max = nil)
  configure(:max_time_ms, max)
end

#max_value(value = nil) ⇒ Hash, View

Set the maximum value to search.

Examples:

Set the max value.

view.max_value(_id: 1)

Parameters:

  • value (Hash) (defaults to: nil)

    The max field and value.

Returns:

  • (Hash, View)

    The value or a new View.

Since:

  • 2.1.0



421
422
423
# File 'lib/mongo/collection/view/readable.rb', line 421

def max_value(value = nil)
  configure(:max_value, value)
end

#min_value(value = nil) ⇒ Hash, View

Set the minimum value to search.

Examples:

Set the min value.

view.min_value(_id: 1)

Parameters:

  • value (Hash) (defaults to: nil)

    The min field and value.

Returns:

  • (Hash, View)

    The value or a new View.

Since:

  • 2.1.0



435
436
437
# File 'lib/mongo/collection/view/readable.rb', line 435

def min_value(value = nil)
  configure(:min_value, value)
end

#modifiers(doc = nil) ⇒ Hash, View

If called without arguments or with a nil argument, returns the legacy (OP_QUERY) server modifiers for the current view. If called with a non-nil argument, which must be a Hash or a subclass, merges the provided modifiers into the current view. Both string and symbol keys are allowed in the input hash.

Examples:

Set the modifiers document.

view.modifiers(:$orderby => Mongo::Index::ASCENDING)

Parameters:

  • doc (Hash) (defaults to: nil)

    The modifiers document.

Returns:

  • (Hash, View)

    Either the modifiers document or a new View.

Since:

  • 2.1.0



579
580
581
582
583
584
585
# File 'lib/mongo/collection/view/readable.rb', line 579

def modifiers(doc = nil)
  if doc.nil?
    Operation::Find::Builder::Modifiers.map_server_modifiers(options)
  else
    new(options.merge(Operation::Find::Builder::Modifiers.map_driver_options(BSON::Document.new(doc))))
  end
end

#no_cursor_timeoutView

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

Examples:

Set the cursor to not timeout.

view.no_cursor_timeout

Returns:

  • (View)

    The new view.

Since:

  • 2.0.0



448
449
450
# File 'lib/mongo/collection/view/readable.rb', line 448

def no_cursor_timeout
  configure(:no_cursor_timeout, true)
end

#projection(document = nil) ⇒ Hash, View

Note:

A value of 0 excludes a field from the doc. A value of 1 includes it. Values must all be 0 or all be 1, with the exception of the _id value. The _id field is included by default. It must be excluded explicitly.

The fields to include or exclude from each doc in the result set.

Examples:

Set the fields to include or exclude.

view.projection(name: 1)

Parameters:

  • document (Hash) (defaults to: nil)

    The field and 1 or 0, to include or exclude it.

Returns:

  • (Hash, View)

    Either the fields or a new View.

Since:

  • 2.0.0



466
467
468
469
# File 'lib/mongo/collection/view/readable.rb', line 466

def projection(document = nil)
  validate_doc!(document) if document
  configure(:projection, document)
end

#read(value = nil) ⇒ Symbol, View

Note:

If none is specified for the query, the read preference of the collection will be used.

The read preference to use for the query.

Parameters:

  • value (Hash) (defaults to: nil)

    The read preference mode to use for the query.

Returns:

  • (Symbol, View)

    Either the read preference or a new View.

Since:

  • 2.0.0



482
483
484
485
# File 'lib/mongo/collection/view/readable.rb', line 482

def read(value = nil)
  return read_preference if value.nil?
  configure(:read, value)
end

#read_concernObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 2.0.0



631
632
633
634
635
636
637
# File 'lib/mongo/collection/view/readable.rb', line 631

def read_concern
  if options[:session] && options[:session].in_transaction?
    options[:session].send(:txn_read_concern) || collection.client.read_concern
  else
    collection.read_concern
  end
end

#read_preferenceObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 2.0.0



640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'lib/mongo/collection/view/readable.rb', line 640

def read_preference
  @read_preference ||= begin
    # Operation read preference is always respected, and has the
    # highest priority. If we are in a transaction, we look at
    # transaction read preference and default to client, ignoring
    # collection read preference. If we are not in transaction we
    # look at collection read preference which defaults to client.
    rp = if options[:read]
      options[:read]
    elsif options[:session] && options[:session].in_transaction?
      options[:session].txn_read_preference || collection.client.read_preference
    else
      collection.read_preference
    end
    Lint.validate_underscore_read_preference(rp)
    rp
  end
end

#return_key(value = nil) ⇒ true, ...

Set whether to return only the indexed field or fields.

Examples:

Set the return key value.

view.return_key(true)

Parameters:

  • value (true, false) (defaults to: nil)

    The return key value.

Returns:

  • (true, false, View)

    The value or a new View.

Since:

  • 2.1.0



497
498
499
# File 'lib/mongo/collection/view/readable.rb', line 497

def return_key(value = nil)
  configure(:return_key, value)
end

#show_disk_loc(value = nil) ⇒ true, ... Also known as: show_record_id

Set whether the disk location should be shown for each document.

Examples:

Set show disk location option.

view.show_disk_loc(true)

Parameters:

  • value (true, false) (defaults to: nil)

    The value for the field.

Returns:

  • (true, false, View)

    Either the value or a new View.

Since:

  • 2.0.0



512
513
514
# File 'lib/mongo/collection/view/readable.rb', line 512

def show_disk_loc(value = nil)
  configure(:show_disk_loc, value)
end

#skip(number = nil) ⇒ Integer, View

The number of docs to skip before returning results.

Examples:

Set the number to skip.

view.skip(10)

Parameters:

  • number (Integer) (defaults to: nil)

    Number of docs to skip.

Returns:

  • (Integer, View)

    Either the skip value or a new View.

Since:

  • 2.0.0



528
529
530
# File 'lib/mongo/collection/view/readable.rb', line 528

def skip(number = nil)
  configure(:skip, number)
end

#snapshot(value = nil) ⇒ Object

Deprecated.

This option is deprecated as of MongoDB server version 4.0.

Note:

When set to true, prevents documents from returning more than once.

Set the snapshot value for the view.

Examples:

Set the snapshot value.

view.snapshot(true)

Parameters:

  • value (true, false) (defaults to: nil)

    The snapshot value.

Since:

  • 2.0.0



546
547
548
# File 'lib/mongo/collection/view/readable.rb', line 546

def snapshot(value = nil)
  configure(:snapshot, value)
end

#sort(spec = nil) ⇒ Hash, View

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

Examples:

Set the sort criteria

view.sort(name: -1)

Parameters:

  • spec (Hash) (defaults to: nil)

    The attributes and directions to sort by.

Returns:

  • (Hash, View)

    Either the sort setting or a new View.

Since:

  • 2.0.0



561
562
563
# File 'lib/mongo/collection/view/readable.rb', line 561

def sort(spec = nil)
  configure(:sort, spec)
end