Sat, 26 Jun 2010 20:00:53 EST
finding things in a mongo database
The generic method dbfind provides the basic query interface in cl-mongo. It's defined as:
(defgeneric db.find (collection kv &key) )
db.find returns documents in the collection which satisfy the query pattern specified by the bson document kv. If you use the keyword :all db.find will return all documents. If you're looking for all documents with specific (key value) pair you'd specify that those as the query pattern :
(db.find "foo" (kv (kv "k" 3) (kv "l" 4)))
db.find returns a header and a list of documents. A single call to db.find returns at most a 100 documents or whatever mongodb has set as the limit to return in a single call. To get more documents you'd need to query the database with the iterator object returned by db.find. The convenience function iter does exactly that. So, in order to return all documents in collection "foo" you'd call :
(pp (iter (db.find "foo" :all)))
pp is a pretty printer provided by cl_mongo. Alternatively, you can use the docs function to convert the results of the query in a list of documents for further processing. Both pp and docs will properly clean up the iterator object.
db.find accepts a number of keywords. The keyword :limit defines the maximum number of documents returned, with 1 as it's default. However when the query pattern is :all it will in fact be 0, and hence db.find will return the maximum number of documents allowable by mongodb. In all other cases, since the default value of :limit is 1, db.find is the equivalent of findOne in the mongo documentation.
Unsurprisingly, you can specify the number of documents to skip in this query with :skip. It's default is 0.
The :selector keyword allows you to select which keys to return. For example, if you just want to return the "_id" field for the objects in foo, you'd specify :
(pp (iter (db.find "foo" :all :selector "_id" )))
The keyword :mongo allows you to specify a connection other than the default connection.
The keyword :options is used to specify query options and will be covered elsewhere.