mongodbclojuremonger

When using monger, do I need to supply connection each request?


In the documentation, the mongodb connection is established once, before being used without passing the connection to each command, is that the proper way to use monger, or should I pass the database connection to each call?


Solution

  • If you work with single database then it's best to set the connection once:

    (mg/connect! db-spec)
    

    But it's not a good idea when you have multiple databases. Monger have with-connection macro (see API docs) for this case:

    (mg/with-connection db-connection
      ...)
    

    You may establish all connections once during the initialization of your app:

    (def conn1 (mg/connect db-spec))
    

    and then use them:

    (mg/with-connection conn1
      ...)
    

    Update. In our application we have a hash-map of all database connections:

    (def  ^:dynamic
          ^clojure.lang.PersistentArrayMap
          *connections*
          {})
    
    (defn connect! [db]
      {:pre [(contains? mongo-config db)]}
      (if (-> db *connections* nil?)
          (let [conn (mg/connect (get mongo-config db))]
            (alter-var-root #'*connections*
                            assoc
                            db
                            { :conn conn
                              :db   (mg/get-db conn (name db))})))
      (-> *connections* db :conn))
    
    (defmacro with-db [db & body]
      "Eval body using :amonplus or :statistic db"
      `(mg/with-connection (connect! ~db)
        (mg/with-db        (clojure.core/-> *connections* ~db :db)
          ~@body)))
    

    mongo-config variable stores specification for all our databases and with-db macro makes it easy to access them by their names:

    (with-db :my-db
      ...)