我怀疑您在某处有错误,并建议您检查游标查询的结果(例如 p collection.find(query).to_a)与集合(例如 p collection.find.to_a)。以下适用于 Ruby 1.9.3、Mongo 2.0.4、mongo-ruby-driver 1.6.2。我希望它有所帮助,也许您可以验证它是否也适用于您并且可以收敛到解决方案。
MongoConfig.rb
require "mongo"
KEY = 'my_key'
module MongoConfig
SERVER = 'localhost'
PORT = Mongo::Connection::DEFAULT_PORT
DB = 'my_db'
COLLECTION = 'my_collection'
attr_accessor :db, :collection
def configure
@server = SERVER
@port = PORT
end
def init_collection(connection)
@db = connection[MongoConfig::DB]
@collection = @db[MongoConfig::COLLECTION]
return @collection
end
end
blocking_mongo_fetcher_test.rb
$LOAD_PATH.unshift(File.expand_path("..", __FILE__))
require "test-unit"
require "MongoConfig"
require "BlockingMongoFetcher"
class BlockingMongoFetcherTest < Test::Unit::TestCase
def setup
clear_collection
end
def clear_collection
Mongo::Connection.new[MongoConfig::DB][MongoConfig::COLLECTION].remove
end
def count_various_ways_and_cursor_twice_test
value = 'my name'
query = {KEY => value}
count_command = {'count' => MongoConfig::COLLECTION, 'query' => { KEY => value} }
fetcher = BlockingMongoFetcher.new
assert_equal(0, fetcher.collection.count) # collection count
assert_equal(0, fetcher.collection.find(query).count) # cursor count
assert_equal(0, fetcher.db.command(count_command)['n'].to_i) # db command count
assert_nil(fetcher.fetch(value))
fetcher.collection.insert({KEY => value})
fetcher.collection.insert({KEY => 'x'})
assert_equal(2, fetcher.collection.count) # collection count
assert_equal(1, fetcher.collection.find(query).count) # cursor count
assert_equal(1, fetcher.db.command(count_command)['n'].to_i) # db command count
assert_equal(value, fetcher.fetch(value)[KEY])
cursor = fetcher.collection.find(query)
assert_equal(1, cursor.count) # check once
assert_equal(1, cursor.count) # check twice
end
test "basic test" do
count_various_ways_and_cursor_twice_test
end
test "repeated test" do
100.times do
clear_collection
count_various_ways_and_cursor_twice_test
end
end
end