2017-06-26 73 views
0

如何在Monger中使用find-maps時設置ReadPreference?該蒙格文件只規定如這樣做是設置讀取偏好,同時連接到蒙戈以下在Clojure MongoDb驅動程序Monger中設置ReadPreference

(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

一種方式與monger.query與收集的用法:

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

如果」重新考慮在Java API中使用此方法:https://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/DBCollection.html#setReadPreference-com.mongodb.ReadPreference-我沒有找到通過monger使用此方法的方法。但是,您可以推出自己的功能以利用此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)))) 
相關問題