Setting ReadPreference in Clojure MongoDb Driver Monger

124 Views Asked by At

How do I set ReadPreference while using find-maps in Monger ? The Monger documentation only specifies the usage with with-collection of monger.query as shown below

(ns my.service.server
(:refer-clojure :exclude [sort find])
(:require [monger.core :as mg]
        [monger.query :refer :all])
(:import com.mongodb.ReadPreference))

(let [conn (mg/connect)
  db   (mg/get-db conn "monger-test")
  coll "scores"]
;; reads from primary (master) to guarantee consistency
;; (at the cost of putting extra load on the primary)
(with-collection db coll
(find {:email "[email protected]"})
(read-preference (ReadPreference/primary))))
1

There are 1 best solutions below

0
On

One way of doing it is setting the read preference while connecting to Mongo:

(mg/connect
  (mg/server-address "127.0.0.1" 27017)
  (mg/mongo-options {:read-preference (com.mongodb.ReadPreference/secondaryPreferred)}))

If you're thinking about using this method in the Java API: https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/DBCollection.html#setReadPreference-com.mongodb.ReadPreference- I did not find a way to use this via monger. However, you can roll your own functions to take advantage of this API:

(defn find-with-read-preference [db coll]
  (.find (doto
           (.getCollection db (name coll))
           (.setReadPreference (ReadPreference/secondaryPreferred)))))

(defn find-maps-with-read-preference
  ([^DB db ^String coll]
   (with-open [result (find-with-read-preference db coll)]
     (map (fn [x] (monger.conversion/from-db-object x true)) result))))