Method: Mongo::Collection#find

Defined in:
lib/mongo/collection.rb

#find(selector = {}, opts = {}) ⇒ Object

Query the database.

The selector argument is a prototype document that all results must match. For example:

collection.find({"hello" => "world"})

only matches documents that have a key “hello” with value “world”. Matches can have other keys *in addition* to “hello”.

If given an optional block find will yield a Cursor to that block, close the cursor, and then return nil. This guarantees that partially evaluated cursors will be closed. If given no block find returns a cursor.

Parameters:

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

    a document specifying elements which must be present for a document to be included in the result set. Note that in rare cases, (e.g., with $near queries), the order of keys will matter. To preserve key order on a selector, use an instance of BSON::OrderedHash (only applies to Ruby 1.8).

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

    a customizable set of options

Options Hash (opts):

  • :fields (Array, Hash)

    field names that should be returned in the result set (“_id” will be included unless explicitly excluded). By limiting results to a certain subset of fields, you can cut down on network traffic and decoding time. If using a Hash, keys should be field names and values should be either 1 or 0, depending on whether you want to include or exclude the given field.

  • :read (:primary, :secondary)

    The default read preference for queries initiates from this connection object. If :secondary is chosen, reads will be sent to one of the closest available secondary nodes. If a secondary node cannot be located, the read will be sent to the primary. If this option is left unspecified, the value of the read preference for this Collection object will be used.

  • :skip (Integer)

    number of documents to skip from the beginning of the result set

  • :limit (Integer)

    maximum number of documents to return

  • :sort (Array)

    an array of [key, direction] pairs to sort by. Direction should be specified as Mongo::ASCENDING (or :ascending / :asc) or Mongo::DESCENDING (or :descending / :desc)

  • :hint (String, Array, OrderedHash)

    hint for query optimizer, usually not necessary if using MongoDB > 1.1

  • :snapshot (Boolean) — default: false

    if true, snapshot mode will be used for this query. Snapshot mode assures no duplicates are returned, or objects missed, which were preset at both the start and end of the query’s execution. For details see www.mongodb.org/display/DOCS/How+to+do+Snapshotting+in+the+Mongo+Database

  • :batch_size (Boolean) — default: 100

    the number of documents to returned by the database per GETMORE operation. A value of 0 will let the database server decide how many results to return. This option can be ignored for most use cases.

  • :timeout (Boolean) — default: true

    when true, the returned cursor will be subject to the normal cursor timeout behavior of the mongod process. When false, the returned cursor will never timeout. Note that disabling timeout will only work when #find is invoked with a block. This is to prevent any inadvertent failure to close the cursor, as the cursor is explicitly closed when block code finishes.

  • :max_scan (Integer) — default: nil

    Limit the number of items to scan on both collection scans and indexed queries..

  • :show_disk_loc (Boolean) — default: false

    Return the disk location of each query result (for debugging).

  • :return_key (Boolean) — default: false

    Return the index key used to obtain the result (for debugging).

  • :transformer (Block) — default: nil

    a block for transforming returned documents. This is normally used by object mappers to convert each returned document to an instance of a class.

  • :comment (String) — default: nil

    a comment to include in profiling logs

Raises:

  • (ArgumentError)

    if timeout is set to false and find is not invoked in a block

  • (RuntimeError)

    if given unknown options



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
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
# File 'lib/mongo/collection.rb', line 222

def find(selector={}, opts={})
  opts               = opts.dup
  fields             = opts.delete(:fields)
  fields             = ["_id"] if fields && fields.empty?
  skip               = opts.delete(:skip) || skip || 0
  limit              = opts.delete(:limit) || 0
  sort               = opts.delete(:sort)
  hint               = opts.delete(:hint)
  snapshot           = opts.delete(:snapshot)
  batch_size         = opts.delete(:batch_size)
  timeout            = (opts.delete(:timeout) == false) ? false : true
  max_scan           = opts.delete(:max_scan)
  return_key         = opts.delete(:return_key)
  transformer        = opts.delete(:transformer)
  show_disk_loc      = opts.delete(:show_disk_loc)
  comment            = opts.delete(:comment)
  read               = opts.delete(:read) || @read
  tag_sets           = opts.delete(:tag_sets) || @tag_sets
  acceptable_latency = opts.delete(:acceptable_latency) || @acceptable_latency

  if timeout == false && !block_given?
    raise ArgumentError, "Collection#find must be invoked with a block when timeout is disabled."
  end

  if hint
    hint = normalize_hint_fields(hint)
  else
    hint = @hint        # assumed to be normalized already
  end

  raise RuntimeError, "Unknown options [#{opts.inspect}]" unless opts.empty?

  cursor = Cursor.new(self, {
    :selector           => selector,
    :fields             => fields,
    :skip               => skip,
    :limit              => limit,
    :order              => sort,
    :hint               => hint,
    :snapshot           => snapshot,
    :timeout            => timeout,
    :batch_size         => batch_size,
    :transformer        => transformer,
    :max_scan           => max_scan,
    :show_disk_loc      => show_disk_loc,
    :return_key         => return_key,
    :read               => read,
    :tag_sets           => tag_sets,
    :comment            => comment,
    :acceptable_latency => acceptable_latency
  })

  if block_given?
    begin
      yield cursor
    ensure
      cursor.close
    end
    nil
  else
    cursor
  end
end