Permalink
Browse files

Support read preferences for Collection#count().

Also, make Cursor#count inherit the read preference of the cursor.

Add a test case for secondary counts.
  • Loading branch information...
1 parent 6086264 commit 090cd7e154544d7296bcbf46d815449c81a7381a @nelhage committed Dec 5, 2012
Showing with 15 additions and 3 deletions.
  1. +5 −2 lib/mongo/collection.rb
  2. +1 −1 lib/mongo/cursor.rb
  3. +9 −0 test/replica_set/count_test.rb
View
@@ -940,12 +940,15 @@ def stats
# @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.
+ # @option opts [:primary, :secondary] :read Read preference for this command. See Collection#find for
+ # more details.
#
# @return [Integer]
def count(opts={})
find(opts[:query],
- :skip => opts[:skip],
- :limit => opts[:limit]).count(true)
+ :skip => opts[:skip],
+ :limit => opts[:limit],
+ :read => opts[:read]).count(true)
end
alias :size :count
View
@@ -188,7 +188,7 @@ def count(skip_and_limit = false)
command.merge!(BSON::OrderedHash["fields", @fields])
- response = @db.command(command)
+ response = @db.command(command, :read => @read_preference)
return response['n'].to_i if Mongo::Support.ok?(response)
return 0 if response['errmsg'] == "ns missing"
raise OperationFailure.new("Count failed: #{response['errmsg']}", response['code'], response)
@@ -43,4 +43,13 @@ def test_count_command_sent_to_primary
count_after = @primary['admin'].command({:serverStatus => 1})['opcounters']['command']
assert_equal 2, count_after - count_before
end
+
+ def test_count_with_read_preference
+ @coll.insert({:a => 20}, :w => 2, :wtimeout => 10000)
+ count_before = @primary['admin'].command({:serverStatus => 1})['opcounters']['command']
+ assert_equal 1, @coll.count(:read => :secondary)
+ assert_equal 1, @coll.find({}, :read => :secondary).count()
+ count_after = @primary['admin'].command({:serverStatus => 1})['opcounters']['command']
+ assert_equal 1, count_after - count_before
+ end
end

0 comments on commit 090cd7e

Please sign in to comment.