From 3963808152fdaad61e8e5896c445b4e194040d71 Mon Sep 17 00:00:00 2001 From: "Michael S. Klishin" Date: Sun, 16 Oct 2011 14:19:04 +0400 Subject: [PATCH] Introduce monger.collection/distinct --- src/monger/collection.clj | 15 ++++++++++++++- test/monger/test/collection.clj | 17 +++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/monger/collection.clj b/src/monger/collection.clj index 461580a..95ec797 100644 --- a/src/monger/collection.clj +++ b/src/monger/collection.clj @@ -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 diff --git a/test/monger/test/collection.clj b/test/monger/test/collection.clj index 858ba54..17db479 100644 --- a/test/monger/test/collection.clj +++ b/test/monger/test/collection.clj @@ -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 } }))))))