RUBY-307 Collection#count should take a query, skip, and limit.

This commit is contained in:
Kyle Banker 2011-09-06 11:38:19 -04:00
parent b0b1c043ca
commit 834b0db0af
3 changed files with 17 additions and 7 deletions

View File

@ -83,9 +83,9 @@ module Mongo
@cache = Hash.new(0)
unless pk_factory
@safe = opts.fetch(:safe, @db.safe)
@read = opts.fetch(:read, @db.read_preference)
@read_preference = @read.is_a?(Hash) ? @read.dup : @read
end
read = opts.fetch(:read, @db.read_preference)
@read_preference = read.is_a?(Hash) ? read.dup : read
@pk_factory = pk_factory || opts[:pk] || BSON::ObjectId
@hint = nil
end
@ -828,9 +828,15 @@ module Mongo
# Get the number of documents in this collection.
#
# @option opts [Hash] :query ({}) A query selector for filtering the documents counted.
# @option opts [Integer] :skip (nil) The number of documents to skip.
# @option opts [Integer] :limit (nil) The number of documents to limit.
#
# @return [Integer]
def count
find().count()
def count(opts={})
find(opts[:query],
:skip => opts[:skip],
:limit => opts[:limit]).count(true)
end
alias :size :count

View File

@ -18,9 +18,9 @@ module Mongo
# A cursor over query results. Returned objects are hashes.
class Cursor
include Mongo::Conversions
include Enumerable
include Mongo::Constants
include Mongo::Conversions
attr_reader :collection, :selector, :fields,
:order, :hint, :snapshot, :timeout,

View File

@ -314,9 +314,13 @@ class TestCollection < Test::Unit::TestCase
@@test.drop
assert_equal 0, @@test.count
@@test.save("x" => 1)
@@test.save("x" => 2)
@@test.save(:x => 1)
@@test.save(:x => 2)
assert_equal 2, @@test.count
assert_equal 1, @@test.count(:query => {:x => 1})
assert_equal 1, @@test.count(:limit => 1)
assert_equal 0, @@test.count(:skip => 2)
end
# Note: #size is just an alias for #count.