Introduce monger.collection/distinct

This commit is contained in:
Michael S. Klishin 2011-10-16 14:19:04 +04:00
parent d639fab9cf
commit 3963808152
2 changed files with 31 additions and 1 deletions

View file

@ -8,7 +8,7 @@
;; You must not remove this notice, or any other, from this software.
(ns monger.collection
(:refer-clojure :exclude [find remove count drop])
(:refer-clojure :exclude [find remove count drop distinct])
(:import [com.mongodb Mongo DB DBCollection WriteResult DBObject WriteConcern DBCursor MapReduceCommand MapReduceCommand$OutputType]
[java.util List Map]
[clojure.lang IPersistentMap ISeq])
@ -296,6 +296,19 @@
(.mapReduce coll js-mapper js-reducer output output-type (to-db-object query)))))
;;
;; monger.collection/distinct
;;
(defn distinct
([^String collection, ^String key]
(let [^DBCollection coll (.getCollection monger.core/*mongodb-database* collection)]
(.distinct coll ^String (to-db-object key))))
([^String collection, ^String key, ^Map query]
(let [^DBCollection coll (.getCollection monger.core/*mongodb-database* collection)]
(.distinct coll ^String (to-db-object key) ^DBObject (to-db-object query)))))
;;
;; Implementation

View file

@ -552,3 +552,20 @@
(is (= ["CA" "IL" "NY" "OR"]
(map :_id (mgcol/find-maps "merged_mr_outputs"))))
(.drop ^MapReduceOutput output))))
;;
;; distinct
;;
(deftest distinct-values
(let [collection "widgets"
batch [{ :state "CA" :quantity 1 :price 199.00 }
{ :state "NY" :quantity 2 :price 199.00 }
{ :state "NY" :quantity 1 :price 299.00 }
{ :state "IL" :quantity 2 :price 11.50 }
{ :state "CA" :quantity 2 :price 2.95 }
{ :state "IL" :quantity 3 :price 5.50 }]]
(mgcol/insert-batch collection batch)
(is (= ["CA" "IL" "NY"] (sort (mgcol/distinct collection :state))))
(is (= ["CA" "NY"] (sort (mgcol/distinct collection :state { :price { "$gt" 100.00 } }))))))