Initial bits of monger.collection/find and monger.collection/find-by-id

This commit is contained in:
Michael S. Klishin 2011-08-14 08:03:29 +04:00
parent 3bf2284611
commit 11ad2168ed
3 changed files with 72 additions and 3 deletions

View file

@ -19,7 +19,7 @@
;; THE SOFTWARE.
(ns monger.collection
(:import (com.mongodb Mongo DB WriteResult DBObject WriteConcern) (java.util List))
(:import (com.mongodb Mongo DB WriteResult DBObject WriteConcern DBCursor) (java.util List Map))
(:require [monger core convertion errors]))
;;
@ -42,6 +42,22 @@
(.insert (.getCollection db collection) (monger.convertion/to-db-object docs) concern)))
;; monger.collection/find
(defn ^DBCursor find
([^DB db, ^String collection]
(.find (.getCollection db collection)))
([^DB db, ^String collection, ^Map ref]
(.find (.getCollection db collection) (monger.convertion/to-db-object ref)))
)
(defn ^DBObject find-by-id
([^DB db, ^String collection, ^String id]
(.findOne (.getCollection db collection) (monger.convertion/to-db-object { :_id id })))
)
;; monger.collection/group
;; monger.collection/count

11
src/monger/util.clj Normal file
View file

@ -0,0 +1,11 @@
(ns monger.util
(:import (java.security SecureRandom) (java.math.BigInteger)))
;;
;; API
;;
(defn ^String random-str
"Generates a secure random string"
[^long n, ^long num-base]
(.toString (new BigInteger n (SecureRandom.)) num-base))

View file

@ -1,8 +1,8 @@
(set! *warn-on-reflection* true)
(ns monger.test.collection
(:import [com.mongodb WriteResult WriteConcern])
(:require [monger core collection errors] [clojure stacktrace])
(:import [com.mongodb WriteResult WriteConcern DBCursor])
(:require [monger core collection errors util] [clojure stacktrace])
(:use [clojure.test]))
@ -65,3 +65,45 @@
db (monger.core/get-db connection "monger-test")]
(is 0 (monger.collection/count db "things"))))
;;
;; find
;;
(deftest find-full-document-when-collection-is-empty
(let [connection (monger.core/connect)
db (monger.core/get-db connection "monger-test")
collection "docs"]
(monger.collection/remove db collection)
(def cursor (monger.collection/find db collection))
(is (instance? DBCursor cursor))))
;;
;; find-by-id
;;
(deftest find-full-document-by-id-when-document-does-not-exist
(let [connection (monger.core/connect)
db (monger.core/get-db connection "monger-test")
collection "libraries"
doc-id (monger.util/random-str 140 16)]
(monger.collection/remove db collection)
(is (nil? (monger.collection/find-by-id db collection doc-id)))))
(deftest find-full-document-by-id-when-document-exists
(let [connection (monger.core/connect)
db (monger.core/get-db connection "monger-test")
collection "libraries"
doc-id (monger.util/random-str 140 16)
doc { :data-store "MongoDB", :language "Clojure", :_id doc-id }]
(monger.collection/remove db collection)
(monger.collection/insert db collection doc)
(is (= (doc (monger.collection/find-by-id db collection doc-id))))))