I am new to clojure.
Are there any idioms/patterns around connecting to mongodb through monger?
Do I have to connect and disconnect using
(monger.core/connect) & (monger.core/disconnect conn)
respectively. each time ?
Is there a way I can reuse a connection from a connection pool?
monger uses MongoClient, which does connection pooling. After you connect
, you can keep working with that pool until you're done, and then disconnect
. See the monger documentation for supported connection options (e.g. maximum number of connections in the pool, default 10).
We just need example code, right? The documentation only talks about creating locally bound connections through let
, so this will get you started:
(ns pipegen.core
(:require [monger.core :as mg]
[monger.collection :as mc]))
(def conn (atom (mg/connect-via-uri mongo-uri)))
(mc/insert (:db @conn) "collectionname" {:name "methuzula" :age 123})
It wasn't clear to me, from documentation, the return type of mg/connect-via-uri
, so I'll mention briefly in case it helps someone:
{:conn #object[com.mongodb.MongoClient]
:db #object[com.mongodb.DB]}
If you save that to a def
, you can reuse it as needed.
Side Notes, less related to your question, but will probably help you:
This may not be the best design pattern for connecting to dbs. Here are some design patterns for dependency injection I enjoyed reading through, it gives some better ideas of passing around the mongo connection context, the Reader Monad seems particularly cool, I'll have to try it out myself! http://software-ninja-ninja.blogspot.co.il/2014/04/5-faces-of-dependency-injection-in.html
Also, clojurians
on slack
is a friendly community I didn't find out until after many a headache with clojure, check em out! https://clojurians.slack.com/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With