Skip to content

Instantly share code, notes, and snippets.

@rads
Created March 4, 2010 21:20
Show Gist options
  • Save rads/322125 to your computer and use it in GitHub Desktop.
Save rads/322125 to your computer and use it in GitHub Desktop.
(defunk fetch
"Fetches objects from a collection.
Note that MongoDB always adds the _id and _ns
fields to objects returned from the database.
Optional arguments include
:where -> takes a query map
:only -> takes an array of keys to retrieve
:as -> what to return, defaults to :clojure, can also be :json or :mongo
:from -> argument type, same options as above
:skip -> number of records to skip
:limit -> number of records to return
:sort -> takes a sort map
:one? -> defaults to false, use fetch-one as a shortcut
:count? -> defaults to false, use fetch-count as a shortcut"
{:arglists
'([collection :where :only :limit :skip :sort :as :from :one? :count?])}
[coll :where {} :only [] :as :clojure :from :clojure
:one? false :count? false :limit 0 :skip 0 :sort nil]
(let [n-where (coerce where [from :mongo])
n-only (coerce-fields only)
n-col (get-coll coll)
n-limit (if limit (- 0 (Math/abs limit)) 0)
n-sort (when sort (coerce sort [from :mongo]))]
(cond
count? (.getCount n-col n-where n-only)
one? (when-let [m (.findOne
#^DBCollection n-col
#^DBObject n-where
#^DBObject n-only)]
(coerce m [:mongo as]))
:else (when-let [cursor (.find #^DBCollection n-col
#^DBObject n-where
#^DBObject n-only)]
(do
(doto cursor
(.skip (int skip))
(.limit (int n-limit)))
(if n-sort (.sort cursor #^DBObject n-sort))
(coerce cursor [:mongo as] :many :true))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment