Method: Mongo::Collection#count_documents

Defined in:
lib/mongo/collection.rb

#count_documents(filter = {}, options = {}) ⇒ Integer

Gets the number of documents matching the query. Unlike the deprecated #count method, this will return the exact number of documents matching the filter (or exact number of documents in the collection, if no filter is provided) rather than an estimate.

Use #estimated_document_count to retrieve an estimate of the number of documents in the collection using the collection metadata.

Parameters:

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

    A filter for matching documents.

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

    Options for the operation.

Options Hash (options):

  • :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 (Session)

    The session to use.

  • :comment (Object)

    A user-provided comment to attach to this command.

  • :timeout_ms (Integer)

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the value is inherited from the collection or the database or the client.

Returns:

  • (Integer)

    The document count.

Since:

  • 2.6.0



719
720
721
# File 'lib/mongo/collection.rb', line 719

def count_documents(filter = {}, options = {})
  View.new(self, filter, options).count_documents(options)
end