mongodbclojuremonger

Read-only connection to a slave instance using monger


I have a replica set and I want to establish standalone read-only connection to a slave instance.

Normally, I should experience no problems doing it. The only thing I ought to do is to set slaveOk=true to be able to query it with read operations. It works great when I'm using nodejs or mongo console, but I found no way to do it using monger.

The strangest thing is that I'm getting an exception when I'm calling set-db! function:

MongoException not talking to master and retries used up com.mongodb.DBTCPConnector.innerCall (DBTCPConnector.java:314)

Establishing replica-set connection is not an option for me.

Currently I'm using [com.novemberain/monger "1.4.0"].

Thanks!


Update: I looked through Java MongoDB Driver API Documentation and found slaveOk method. I wrote the following code, hoping it'll work:

(defn slave-connect!
  [& args]
  (mg/set-connection!
    (doto (apply mg/connect args)
          (.slaveOk))))

But all I've got is a new exception:

MongoException not master com.mongodb.CommandResult.getException (CommandResult.java:100)


Solution

  • Looks like I solved my problem using com.mongodb.DBApiLayer Documentation.

    So, the right solution is to set ReadPreference to secondary using setReadPreference method and then to make the database read-only using setReadOnly() method:

    (import 'com.mongodb.ReadPreference)
    
    (defn use-slave-db!
      [& args]
      (mg/set-db!
        (doto (apply mg/get-db args)
              (.setReadOnly true)
              (.setReadPreference
                (ReadPreference/secondary)))))
    

    Now whe are able to connect to a slave instance using use-slave-db! function instead of default use-db! macro.