Method: Mongo::Collection::View::Readable#count_documents

Defined in:
lib/mongo/collection/view/readable.rb

#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:

  • (defaults to: {})

    Options for the operation.

  • 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:

  • The document count.

Since:

  • 2.6.0

API:

  • semipublic



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