Fun with Clojure and MongoDB


Personally I think that writing SQL queries is the most boring task in the IT world, because there exists a large variety of software elements (have you ever heard the word ORM?) that do the job for you.
Since Clojure have no objects, so no impedance mismatch, I thought it would be interesting to combine the Clojure learning and the everyday use with a NoSQL database, such as MongoDB.
There are no particular reasons why I’ve choose MongoDB, but it seems to me quite well-written and easy to use. Clojure provides a simple wrapper to the MongoDB API, the module is called congomongo, and it is installable via leningen in the usual way (add a line into the dependency section of your project.clj).

Remember to start mongod!

Like most databases in the world, MongoDB needs a deamon to dispatch the request to the database: such deamon’s name is mongod. Once installed MongoDB start mongod from console: now your applications can talk with MongoDB.

Fun with Clojure

The following code has the purpose to show some simple operations of fetch, insert and fetch with conditions:

;;Fun with MongoDB
(ns mongofun
  (:use somnium.congomongo))

;;It tells to mongo wich DB you want to use/create
(mongo! :db "mongofun")

;; A simple insert, you have to pass a map of key-value
(insert! :exams {:name "OOP" :vote 29})

;; A simple binding used to show all your exams
(def my-exams (fetch :exams))

;; A general purpose function for inserting an exam
(defn insert-exam [exam-map]
     (insert! :exams exam-map))

;; A list of maps, 1 map = 1 exam
(def exams-list [{:name "Computer Graphics" :vote 30}
		  {:name "IA" :vote 30}
		  {:name "BD2" :vote 30}])

;; Loop over exams-list, insert all the exams
(for [e exams-list] (insert-exam e))

;;Retrieve all the exams where I've took 30
(fetch :exams :where {:vote 30})

This is only a short snipped, but the interesting things is that I haven’t wrote a single line of SQL.
You can see all the exams with my-exams func.
Bye!

Alfredo

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...