diff --git a/lib/mongo/cursor.rb b/lib/mongo/cursor.rb index d42a3bb..e9570ed 100644 --- a/lib/mongo/cursor.rb +++ b/lib/mongo/cursor.rb @@ -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" diff --git a/test/cursor_test.rb b/test/cursor_test.rb index 86ae9f1..e7ae52d 100644 --- a/test/cursor_test.rb +++ b/test/cursor_test.rb @@ -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()