diff --git a/src/clojure/monger/collection.clj b/src/clojure/monger/collection.clj index 0b9a73a..d244c3c 100644 --- a/src/clojure/monger/collection.clj +++ b/src/clojure/monger/collection.clj @@ -404,6 +404,17 @@ multi write-concern))) +(defn ^WriteResult upsert + "Performs an upsert. + + This is a convenience function that delegates to monger.collection/update and + sets :upsert to true. + + See monger.collection/update documentation" + [^String collection ^Map conditions ^Map document & {:keys [upsert multi write-concern] :or {multi false + write-concern monger.core/*mongodb-write-concern*}}] + (update collection conditions document :multi multi :write-concern write-concern)) + (defn ^WriteResult update-by-id "Update a document with given id" [^String collection id ^Map document & {:keys [upsert write-concern] :or {upsert false diff --git a/test/monger/test/updating_test.clj b/test/monger/test/updating_test.clj index e6f71d9..93699a3 100644 --- a/test/monger/test/updating_test.clj +++ b/test/monger/test/updating_test.clj @@ -137,7 +137,7 @@ -(deftest ^{:updating true} upsert-a-document +(deftest ^{:updating true} upsert-a-document-using-update (let [collection "libraries" doc-id (monger.util/random-uuid) date (Date.) @@ -149,3 +149,16 @@ (is (= 1 (mc/count collection))) (is (= (modified-doc (mc/find-by-id collection doc-id)))) (mc/remove collection))) + +(deftest ^{:updating true} upsert-a-document-using-upsert + (let [collection "libraries" + doc-id (monger.util/random-uuid) + date (Date.) + doc {:created-at date :data-store "MongoDB" :language "Clojure" :_id doc-id} + modified-doc {:created-at date :data-store "MongoDB" :language "Erlang" :_id doc-id}] + (is (not (monger.result/updated-existing? (mc/upsert collection {:language "Clojure"} doc)))) + (is (= 1 (mc/count collection))) + (is (monger.result/updated-existing? (mc/upsert collection {:language "Clojure"} modified-doc :multi false))) + (is (= 1 (mc/count collection))) + (is (= (modified-doc (mc/find-by-id collection doc-id)))) + (mc/remove collection)))