2

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)

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122

2 Answers2

2

I found the following works too under monger 2.0.0:

(connect-via-uri "mongodb://host/db?readOnly=true&readPreference=secondary")
Matt
  • 550
  • 4
  • 8
  • Good catch! Though, using Connection String doesn't seem like a proper way of implementing this functionality. – Leonid Beschastny Dec 03 '14 at 18:15
  • 2
    Where did you know about "readOnly" parameter in connection string? It's not listed in [the manual](https://docs.mongodb.com/manual/reference/connection-string/), so I doubt it has any impact here. – Scadge Dec 16 '20 at 11:20
1

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.

Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122