mongodbにclouserからアクセスしてみよう的な。
leinでプロジェクトを作成したら、project.cljに以下の内容を追加します。
(defproject advent "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.5.1"]
[com.novemberain/monger "1.4.2"]])
lein replでインストールを開始します。
$lein repl
Retrieving com/novemberain/monger/1.4.2/monger-1.4.2.pom from clojars
Retrieving org/clojure/clojure/1.4.0/clojure-1.4.0.pom from central
Retrieving org/mongodb/mongo-java-driver/2.10.1/mongo-java-driver-2.10.1.pom from central
Retrieving com/novemberain/validateur/1.2.0/validateur-1.2.0.pom from clojars
Retrieving org/clojure/clojure/1.3.0/clojure-1.3.0.pom from central
Retrieving clojurewerkz/support/0.6.0/support-0.6.0.pom from clojars
Retrieving com/google/guava/guava/12.0/guava-12.0.pom from central
Retrieving com/google/guava/guava-parent/12.0/guava-parent-12.0.pom from central
Retrieving com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.pom from central
Retrieving clojurewerkz/support/0.10.0/support-0.10.0.pom from clojars
Retrieving ragtime/ragtime.core/0.3.0/ragtime.core-0.3.0.pom from clojars
Retrieving org/clojure/tools.cli/0.2.2/tools.cli-0.2.2.pom from central
Retrieving org/clojure/pom.contrib/0.0.25/pom.contrib-0.0.25.pom from central
Retrieving com/google/guava/guava/12.0/guava-12.0.jar from central
Retrieving org/mongodb/mongo-java-driver/2.10.1/mongo-java-driver-2.10.1.jar from central
Retrieving com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9.jar from central
Retrieving org/clojure/tools.cli/0.2.2/tools.cli-0.2.2.jar from central
Retrieving com/novemberain/validateur/1.2.0/validateur-1.2.0.jar from clojars
Retrieving clojurewerkz/support/0.10.0/support-0.10.0.jar from clojars
Retrieving com/novemberain/monger/1.4.2/monger-1.4.2.jar from clojars
Retrieving ragtime/ragtime.core/0.3.0/ragtime.core-0.3.0.jar from clojars
nREPL server started on port 50070 on host 127.0.0.1
REPL-y 0.3.0
Clojure 1.5.1
Docs: (doc function-name-here)
(find-doc "part-of-name-here")
Source: (source function-name-here)
Javadoc: (javadoc java-object-or-class-here)
Exit: Control+D or (exit) or (quit)
Results: Stored in vars *1, *2, *3, an exception in *e
user=>
さっそくいれてみましょう
(require '[monger.core :as m])
(require '[monger.collection :as c])
(import '[org.bson.types ObjectId])
importがおわったら接続してみます。
user=> (m/connect!)
#<MongoClient Mongo: /127.0.0.1:27017>
user=> (m/set-db! (m/get-db "advent"))
#<GridFS com.mongodb.gridfs.GridFS@201ba640>
データーをいれてみます。
user=> (c/insert "documents" { :_id (ObjectId.) :first_name "Finalvent" :last_name "Advent" })
#<WriteResult { "serverUsed" : "/127.0.0.1:27017" , "n" : 0 , "connectionId" : 2 , "err" : null , "ok" : 1.0}>
そして読み出し
user=> (c/find-maps "documents")
({:_id #<ObjectId 52baae6aef86291cc0b82778>, :first_name "Finalvent", :last_name "Advent”})
読める、読めるぞー!(TM
というわけでclojureからもmongodbは便利に使えます。