Query and update documents residing on a MongoDB server(s)
- data Connected m a
- runConn :: Connected m a -> Connection -> m (Either Failure a)
- class (Context Connection m, Context MasterOrSlaveOk m, Context WriteMode m, Throw Failure m, Throw IOError m, MonadIO' m) => Conn m
- data Failure
- = CursorNotFoundFailure CursorId
- | QueryFailure String
- | WriteFailure ErrorCode String
- type Database = UString
- allDatabases :: Conn m => m [Database]
- class (Context Database m, Conn m) => DbConn m
- useDb :: Database -> ReaderT Database m a -> m a
- thisDatabase :: DbConn m => m Database
- type Username = UString
- type Password = UString
- auth :: DbConn m => Username -> Password -> m Bool
- type Collection = UString
- allCollections :: DbConn m => m [Collection]
- data Selection = Select {
- selector :: Selector
- coll :: Collection
- type Selector = Document
- whereJS :: Selector -> Javascript -> Selector
- class Select aQueryOrSelection where
- select :: Selector -> Collection -> aQueryOrSelection
- data WriteMode
- writeMode :: Conn m => WriteMode -> m a -> m a
- insert :: DbConn m => Collection -> Document -> m Value
- insert_ :: DbConn m => Collection -> Document -> m ()
- insertMany :: DbConn m => Collection -> [Document] -> m [Value]
- insertMany_ :: DbConn m => Collection -> [Document] -> m ()
- save :: DbConn m => Collection -> Document -> m ()
- replace :: DbConn m => Selection -> Document -> m ()
- repsert :: DbConn m => Selection -> Document -> m ()
- type Modifier = Document
- modify :: DbConn m => Selection -> Modifier -> m ()
- delete :: DbConn m => Selection -> m ()
- deleteOne :: DbConn m => Selection -> m ()
- slaveOk :: Conn m => m a -> m a
- data Query = Query {}
- data QueryOption
- type Projector = Document
- type Limit = Word32
- type Order = Document
- type BatchSize = Word32
- explain :: DbConn m => Query -> m Document
- find :: DbConn m => Query -> m Cursor
- findOne :: DbConn m => Query -> m (Maybe Document)
- count :: DbConn m => Query -> m Int
- distinct :: DbConn m => Label -> Selection -> m [Value]
- data Cursor
- next :: Conn m => Cursor -> m (Maybe Document)
- nextN :: Conn m => Int -> Cursor -> m [Document]
- rest :: Conn m => Cursor -> m [Document]
- data Group = Group {
- gColl :: Collection
- gKey :: GroupKey
- gReduce :: Javascript
- gInitial :: Document
- gCond :: Selector
- gFinalize :: Maybe Javascript
- data GroupKey
- = Key [Label]
- | KeyF Javascript
- group :: DbConn m => Group -> m [Document]
- data MapReduce = MapReduce {}
- type MapFun = Javascript
- type ReduceFun = Javascript
- type FinalizeFun = Javascript
- mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce
- runMR :: DbConn m => MapReduce -> m Cursor
- runMR' :: DbConn m => MapReduce -> m Document
- type Command = Document
- runCommand :: DbConn m => Command -> m Document
- runCommand1 :: DbConn m => UString -> m Document
- eval :: DbConn m => Javascript -> m Document
Connected
Monad with access to a Connection
, MasterOrSlaveOk
, and WriteMode
, and throws a Failure
on read/write failure and IOError on connection failure
MonadTrans Connected | |
Throw IOError m => Throw IOError (Connected m) | |
Monad m => Throw Failure (Connected m) | |
Monad m => Context Connection (Connected m) | |
Monad m => Context MasterOrSlaveOk (Connected m) | |
Monad m => Context WriteMode (Connected m) | |
Monad m => Monad (Connected m) | |
Monad m => Functor (Connected m) | |
Monad m => Applicative (Connected m) | |
MonadIO m => MonadIO (Connected m) |
class (Context Connection m, Context MasterOrSlaveOk m, Context WriteMode m, Throw Failure m, Throw IOError m, MonadIO' m) => Conn m Source
A monad with access to a Connection
, MasterOrSlaveOk
, and WriteMode
, and throws Failure
on read/write failure and IOError
on connection failure
Read or write exception like cursor expired or inserting a duplicate key.
Note, unexpected data from the server is not a Failure, rather it is a programming error (you should call error
in this case) because the client and server are incompatible and requires a programming change.
CursorNotFoundFailure CursorId | Cursor expired because it wasn't accessed for over 10 minutes, or this cursor came from a different server that the one you are currently connected to (perhaps a fail over happen between servers in a replica set) |
QueryFailure String | Query failed for some reason as described in the string |
WriteFailure ErrorCode String | Error observed by getLastError after a write, error description is in string |
Database
allDatabases :: Conn m => m [Database]Source
List all databases residing on server
thisDatabase :: DbConn m => m DatabaseSource
Current database in use
Authentication
auth :: DbConn m => Username -> Password -> m BoolSource
Authenticate with the database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new connection.
Collection
type Collection = UStringSource
Collection name (not prefixed with database)
allCollections :: DbConn m => m [Collection]Source
List all collections in this database
Selection
Selects documents in collection that match selector
Select | |
|
type Selector = DocumentSource
Filter for a query, analogous to the where clause in SQL. []
matches all documents in collection. [x =: a, y =: b]
is analogous to where x = a and y = b
in SQL. See http://www.mongodb.org/display/DOCS/Querying for full selector syntax.
whereJS :: Selector -> Javascript -> SelectorSource
Add Javascript predicate to selector, in which case a document must match both selector and predicate
class Select aQueryOrSelection whereSource
select :: Selector -> Collection -> aQueryOrSelectionSource
Write
WriteMode
Default write-mode is Unsafe
Insert
insert :: DbConn m => Collection -> Document -> m ValueSource
Insert document into collection and return its "_id" value, which is created automatically if not supplied
insertMany :: DbConn m => Collection -> [Document] -> m [Value]Source
Insert documents into collection and return their "_id" values, which are created automatically if not supplied
insertMany_ :: DbConn m => Collection -> [Document] -> m ()Source
Same as insertMany
except don't return _ids
Update
save :: DbConn m => Collection -> Document -> m ()Source
Save document to collection, meaning insert it if its new (has no "_id" field) or update it if its not new (has "_id" field)
replace :: DbConn m => Selection -> Document -> m ()Source
Replace first document in selection with given document
repsert :: DbConn m => Selection -> Document -> m ()Source
Replace first document in selection with given document, or insert document if selection is empty
type Modifier = DocumentSource
Update operations on fields in a document. See http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations
modify :: DbConn m => Selection -> Modifier -> m ()Source
Update all documents in selection using given modifier
Delete
Read
slaveOk :: Conn m => m a -> m aSource
Ok to execute given action against slave, ie. eventually consistent reads
Query
Use select
to create a basic query with defaults, then modify if desired. For example, (select sel col) {limit = 10}
Query | |
|
data QueryOption Source
TailableCursor | Tailable means cursor is not closed when the last data is retrieved. Rather, the cursor marks the final object's position. You can resume using the cursor later, from where it was located, if more data were received. Like any latent cursor, the cursor may become invalid at some point for example if the final object it references were deleted. Thus, you should be prepared to requery on CursorNotFound exception. |
NoCursorTimeout | |
AwaitData | Use with TailableCursor. If we are at the end of the data, block for a while rather than returning no data. After a timeout period, we do return as normal. |
type Projector = DocumentSource
Fields to return, analogous to the select clause in SQL. []
means return whole document (analogous to * in SQL). [x =: 1, y =: 1]
means return only x
and y
fields of each document. [x =: 0]
means return all fields except x
.
Maximum number of documents to return, i.e. cursor will close after iterating over this number of documents. 0 means no limit.
Fields to sort by. Each one is associated with 1 or -1. Eg. [x =: 1, y =: -1]
means sort by x
ascending then y
descending
The number of document to return in each batch response from the server. 0 means use Mongo default.
findOne :: DbConn m => Query -> m (Maybe Document)Source
Fetch first document satisfying query or Nothing if none satisfy it
count :: DbConn m => Query -> m IntSource
Fetch number of documents satisfying query (including effect of skip and/or limit if present)
distinct :: DbConn m => Label -> Selection -> m [Value]Source
Fetch distinct values of field in selected documents
Cursor
Iterator over results of a query. Use next
to iterate or rest
to get all results. A cursor is closed when it is explicitly closed, all results have been read from it, garbage collected, or not used for over 10 minutes (unless NoCursorTimeout
option was specified in Query
). Reading from a closed cursor raises a CursorNotFoundFailure
. Note, a cursor is not closed when the connection is closed, so you can open another connection to the same server and continue using the cursor.
next :: Conn m => Cursor -> m (Maybe Document)Source
Return next document in query result, or Nothing if finished.
nextN :: Conn m => Int -> Cursor -> m [Document]Source
Return next N documents or less if end is reached
Group
Groups documents in collection by key then reduces (aggregates) each group
Group | |
|
Fields to group by, or function (doc -> key
) returning a key object to be used as the grouping key. Use KeyF instead of Key to specify a key that is not an existing member of the object (or, to access embedded members).
group :: DbConn m => Group -> m [Document]Source
Execute group query and return resulting aggregate value for each distinct key
MapReduce
Maps every document in collection to a list of (key, value) pairs, then for each unique key reduces all its associated values from all lists to a single result. There are additional parameters that may be set to tweak this basic operation.
MapReduce | |
|
type MapFun = JavascriptSource
() -> void
. The map function references the variable this
to inspect the current object under consideration. The function must call emit(key,value)
at least once, but may be invoked any number of times, as may be appropriate.
type ReduceFun = JavascriptSource
(key, value_array) -> value
. The reduce function receives a key and an array of values and returns an aggregate result value. The MapReduce engine may invoke reduce functions iteratively; thus, these functions must be idempotent. That is, the following must hold for your reduce function: for all k, vals : reduce(k, [reduce(k,vals)]) == reduce(k,vals)
. If you need to perform an operation only once, use a finalize function. The output of emit (the 2nd param) and reduce should be the same format to make iterative reduce possible.
type FinalizeFun = JavascriptSource
(key, value) -> final_value
. A finalize function may be run after reduction. Such a function is optional and is not necessary for many map/reduce cases. The finalize function takes a key and a value, and returns a finalized value.
mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduceSource
MapReduce on collection with given map and reduce functions. Remaining attributes are set to their defaults, which are stated in their comments.
runMR :: DbConn m => MapReduce -> m CursorSource
Run MapReduce and return cursor of results. Error if map/reduce fails (because of bad Javascript) TODO: Delete temp result collection when cursor closes. Until then, it will be deleted by the server when connection closes.
runMR' :: DbConn m => MapReduce -> m DocumentSource
Run MapReduce and return a result document containing a result field holding the output Collection and additional statistic fields. Error if the map/reduce failed (because of bad Javascript).
Command
A command is a special query or action against the database. See http://www.mongodb.org/display/DOCS/Commands for details.
runCommand :: DbConn m => Command -> m DocumentSource
Run command against the database and return its result
runCommand1 :: DbConn m => UString -> m DocumentSource
runCommand1 foo = runCommand [foo =: 1]
eval :: DbConn m => Javascript -> m DocumentSource
Run code on server