From 345ee691eb9990b615041d103f91684ff73b7cdc Mon Sep 17 00:00:00 2001 From: "Michael S. Klishin" Date: Sat, 18 Feb 2012 19:02:43 +0400 Subject: [PATCH] Introduce monger.collection/remove-by-id --- ChangeLog.md | 6 +++--- src/monger/collection.clj | 10 ++++++++++ test/monger/test/collection.clj | 8 ++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 253ccc3..c7ef9da 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -55,7 +55,7 @@ monger.collection/find-map-by-id no longer ignore fields argument. Contributed b `monger.core` will eventually be moved there, but not for 1.0. Contributed by Toby Hede. -### monger.collection/update-by-id +### New convenience functions: monger.collection/update-by-id, /remove-by-id -monger.collection/update-by-id is a new convenience function for updating a single document with -given ObjectId +`monger.collection/update-by-id` is a new convenience function for updating a single document with +given ObjectId. `monger.collection/remove-by-id` is its counterpart for removing documents. diff --git a/src/monger/collection.clj b/src/monger/collection.clj index bf209eb..2c7585c 100644 --- a/src/monger/collection.clj +++ b/src/monger/collection.clj @@ -318,6 +318,7 @@ "Update a document with given id" [^String collection ^ObjectId id ^Map document & { :keys [upsert write-concern] :or { upsert false write-concern monger.core/*mongodb-write-concern* } }] + (check-not-nil! id "id must not be nil") (let [^DBCollection coll (.getCollection monger.core/*mongodb-database* collection)] (.update coll (to-db-object { :_id id }) (to-db-object document) upsert false write-concern))) @@ -368,6 +369,15 @@ (.remove coll (to-db-object conditions))))) +(defn ^WriteResult remove-by-id + "Removes a single document with given id" + ([^String collection ^ObjectId id] + (remove-by-id monger.core/*mongodb-database* collection id)) + ([^DB db ^String collection ^ObjectId id] + (check-not-nil! id "id must not be nil") + (let [^DBCollection coll (.getCollection db collection)] + (.remove coll (to-db-object { :_id id }))))) + ;; ;; monger.collection/create-index diff --git a/test/monger/test/collection.clj b/test/monger/test/collection.clj index 7cef427..4915ed9 100644 --- a/test/monger/test/collection.clj +++ b/test/monger/test/collection.clj @@ -62,6 +62,14 @@ (mgcol/remove collection { :language "Clojure" }) (is (= 1 (mgcol/count collection))))) +(deftest remove-a-single-document-from-collection + (let [collection "libraries" + oid (ObjectId.)] + (mgcol/insert-batch collection [{ :language "Clojure" :name "monger" :_id oid }]) + (mgcol/remove-by-id collection oid) + (is (= 0 (mgcol/count collection))) + (is (nil? (mgcol/find-by-id oid))))) + ;; ;; indexes