I’m using the following code to fetch something from mongo:
class BlockingMongoFetcher
include MongoConfig
def initialize
configure
@connection = Mongo::Connection.new(@server, @port)
@collection = init_collection(@connection)
end
def fetch(value)
mongo_cursor = @collection.find({ KEY => value.to_s })
if mongo_cursor.count == 0
# do stuff
return nil
end
if mongo_cursor.count > 1
# do stuff
end
mongo_cursor.first
end
end
init_collection just gets the db and the collection object from the connection.
In the fetch method, I’m using the count method to check, if there are results. Since I got a 0, where there should be 1 item, I added the following code within the gem to the count method of the Cursor class:
if response['n'].to_i == 0
require "ruby-debug"
debugger
puts "stop here"
end
( response = @db.command(command) )
Within the debugger
@db.command(command)['n'].to_i
returns 1. If I call count in the fetch method twice (once without using the output) everything is fine. Am I missing something? Buffer or caching problem? However, this seems not to be deterministic … it only occurs in about 50 % of the runs. Mongodb is 2.0.2 and Ruby 1.9.3p125.
Thanks for your help!
Mhh, unexpected solution:
For inserting test data, I used the following statement within the spec
The insert method has an option :safe, see the API. With the default (false), mongodb stores it async and the code execution continues. This can lead to strange behavior, like the value is not yet in the db, if you query it instantly afterwards. Just use