1

I am start with monger today, the docs use examples like this:

(let [conn (mg/connect)
      db   (mg/get-db conn "monger-test")
      coll "documents"]
  (mc/insert db coll {:first_name "John"  :last_name "Lennon"})
  (mc/insert db coll {:first_name "Ringo" :last_name "Starr"})

  (mc/find db coll {:first_name "Ringo"}))

All documentation examples use that structure. Always connect to MongoDB, then use db on mc/insert... . The question is, how I can put this code on a function and use it in my functions that execute mongodb queries, without repeat below code all time:

(let [conn (mg/connect)
          db   (mg/get-db conn "monger-test")
          coll "documents"] ...

Thanks.

Édipo Féderle
  • 4,169
  • 5
  • 31
  • 35
  • possible duplicate of http://stackoverflow.com/questions/17950969/when-using-monger-do-i-need-to-supply-connection-each-request?rq=1 – Diego Basch Jul 17 '14 at 00:29

2 Answers2

1

Here's how I did it:

(defmacro with-db [body]
  `(let [conn# (mg/connect)
         db# (mg/get-db conn "monger-test")]
    (-> db#
        ~body)))

Used like this:

(with-db (mc/find-maps "mycoll"))
Erik Strömberg
  • 322
  • 4
  • 12
0

you can also do this without defining a macro, using just a plain old function:

(def db-name "monger-test")

(defn with-db [op & args]
  (let [conn    (mongo/connect)
        db      (mongo/get-db conn db-name)]
    (apply op db args)))

(with-db monger.collection/find-maps "test-collection")

will list all the entries in the collection named "test-collection"

732
  • 661
  • 5
  • 12
  • is it right, to instantiate a connection on each function call? Instead, I would think one should define the connecton in a variable once, and then reuse it, wouldn't your connection example incur avoidable performance costs – Josh.F Oct 06 '16 at 18:16