diff --git a/src/monger/query.clj b/src/monger/query.clj index 2b0092a..a4dc99a 100644 --- a/src/monger/query.clj +++ b/src/monger/query.clj @@ -36,14 +36,15 @@ (defn empty-query ([] { - :query {} - :sort {} - :fields [] - :skip 0 - :limit 0 - :batch-size 256 - :hint nil - :snapshot false + :query {} + :sort {} + :fields [] + :skip 0 + :limit 0 + :batch-size 256 + :hint nil + :snapshot false + :keywordize-fields true }) ([^DBCollection coll] (merge (empty-query) { :collection coll }))) @@ -53,7 +54,7 @@ (to-db-object (zipmap fields (repeat 1)))) (defn exec - [{ :keys [collection query fields skip limit sort batch-size hint snapshot read-preference] :or { limit 0 batch-size 256 skip 0 } }] + [{ :keys [collection query fields skip limit sort batch-size hint snapshot read-preference keywordize-fields] :or { limit 0 batch-size 256 skip 0 } }] (let [cursor (doto ^DBCursor (.find ^DBCollection collection (to-db-object query) (fields-to-db-object fields)) (.limit limit) (.skip skip) @@ -64,7 +65,7 @@ (.snapshot cursor)) (when read-preference (.setReadPreference cursor read-preference)) - (map (fn [x] (from-db-object x true)) + (map (fn [x] (from-db-object x keywordize-fields)) (seq cursor)))) ;; @@ -107,6 +108,10 @@ [m ^ReadPreference rp] (merge m { :read-preference rp })) +(defn keywordize-fields + [m bool] + (merge m { :keywordize-fields bool })) + (defn paginate [m & { :keys [page per-page] :or { page 1 per-page 10 } }] (merge m { :limit per-page :skip (monger.internal.pagination/offset-for page per-page) })) diff --git a/test/monger/test/querying.clj b/test/monger/test/querying.clj index ca106d6..7abfc43 100644 --- a/test/monger/test/querying.clj +++ b/test/monger/test/querying.clj @@ -260,3 +260,23 @@ (merge top3) (merge by-population-desc))] (is (= result [ca-doc tx-doc ny-doc])))) + +(deftest combined-querying-dsl-example2 + (let [coll "docs" + ma-doc { :_id (ObjectId.) :name "Massachusetts" :iso "MA" :population 6547629 :joined_in 1788 :capital "Boston" } + de-doc { :_id (ObjectId.) :name "Delaware" :iso "DE" :population 897934 :joined_in 1787 :capital "Dover" } + ny-doc { :_id (ObjectId.) :name "New York" :iso "NY" :population 19378102 :joined_in 1788 :capital "Albany" } + ca-doc { :_id (ObjectId.) :name "California" :iso "CA" :population 37253956 :joined_in 1850 :capital "Sacramento" } + tx-doc { :_id (ObjectId.) :name "Texas" :iso "TX" :population 25145561 :joined_in 1845 :capital "Austin" } + top3 (partial-query (limit 3)) + by-population-desc (partial-query (sort { :population -1 })) + _ (mgcol/insert-batch coll [ma-doc de-doc ny-doc ca-doc tx-doc]) + result (with-collection coll + (find {}) + (merge top3) + (merge by-population-desc) + (keywordize-fields false))] + ;; documents have fields as strings, + ;; not keywords + (is (= (map #(% "name") result) + (map #(% :name) [ca-doc tx-doc ny-doc])))))