Cursor#count now has optional argument to make it take notice of skip and limit

This commit is contained in:
Daniel Cooper 2010-11-15 14:44:33 +00:00 committed by Kyle Banker
parent 8aaed130d6
commit df80704f77
2 changed files with 15 additions and 3 deletions

View File

@ -110,14 +110,22 @@ module Mongo
# Get the size of the result set for this query.
#
# @param [Boolean] whether of not to take notice of skip and limit
#
# @return [Integer] the number of objects in the result set for this query. Does
# not take limit and skip into account.
#
# @raise [OperationFailure] on a database error.
def count
def count skip_and_limit = false
command = BSON::OrderedHash["count", @collection.name,
"query", @selector,
"fields", @fields]
"query", @selector]
if skip_and_limit
command.merge! BSON::OrderedHash["limit", @limit] if @limit != 0
command.merge! BSON::OrderedHash["skip", @skip] if @skip != 0
end
command.merge! BSON::OrderedHash["fields", @fields]
response = @db.command(command)
return response['n'].to_i if Mongo::Support.ok?(response)
return 0 if response['errmsg'] == "ns missing"

View File

@ -46,6 +46,10 @@ class CursorTest < Test::Unit::TestCase
assert_equal 10, @@coll.find({}, :limit => 5).count()
assert_equal 10, @@coll.find({}, :skip => 5).count()
assert_equal 5, @@coll.find({}, :limit => 5).count(true)
assert_equal 5, @@coll.find({}, :skip => 5).count(true)
assert_equal 2, @@coll.find({}, :skip => 5, :limit => 2).count(true)
assert_equal 1, @@coll.find({"x" => 1}).count()
assert_equal 5, @@coll.find({"x" => {"$lt" => 5}}).count()