Safe Haskell | None |
---|
Query and update documents
- data Action m a
- access :: MonadIO m => Pipe -> AccessMode -> Database -> Action m a -> m (Either Failure a)
- data Failure
- type ErrorCode = Int
- data AccessMode
- type GetLastError = Document
- master :: AccessMode
- slaveOk :: AccessMode
- accessMode :: Monad m => AccessMode -> Action m a -> Action m a
- class (Monad m, MonadBaseControl IO (BaseMonad m), Applicative (BaseMonad m), Functor (BaseMonad m)) => MonadDB m where
- type Database = Text
- allDatabases :: MonadIO' m => Action m [Database]
- useDb :: Monad m => Database -> Action m a -> Action m a
- thisDatabase :: Monad m => Action m Database
- type Username = Text
- type Password = Text
- auth :: MonadIO' m => Username -> Password -> Action m Bool
- type Collection = Text
- allCollections :: (MonadIO m, MonadBaseControl IO m, Functor m) => Action m [Collection]
- data Selection = Select {
- selector :: Selector
- coll :: Collection
- type Selector = Document
- whereJS :: Selector -> Javascript -> Selector
- class Select aQueryOrSelection where
- select :: Selector -> Collection -> aQueryOrSelection
- insert :: MonadIO' m => Collection -> Document -> Action m Value
- insert_ :: MonadIO' m => Collection -> Document -> Action m ()
- insertMany :: MonadIO m => Collection -> [Document] -> Action m [Value]
- insertMany_ :: MonadIO m => Collection -> [Document] -> Action m ()
- insertAll :: MonadIO m => Collection -> [Document] -> Action m [Value]
- insertAll_ :: MonadIO m => Collection -> [Document] -> Action m ()
- save :: MonadIO' m => Collection -> Document -> Action m ()
- replace :: MonadIO m => Selection -> Document -> Action m ()
- repsert :: MonadIO m => Selection -> Document -> Action m ()
- type Modifier = Document
- modify :: MonadIO m => Selection -> Modifier -> Action m ()
- delete :: MonadIO m => Selection -> Action m ()
- deleteOne :: MonadIO m => Selection -> Action m ()
- data Query = Query {}
- data QueryOption
- type Projector = Document
- type Limit = Word32
- type Order = Document
- type BatchSize = Word32
- explain :: MonadIO m => Query -> Action m Document
- find :: (MonadIO m, MonadBaseControl IO m) => Query -> Action m Cursor
- findOne :: MonadIO m => Query -> Action m (Maybe Document)
- fetch :: MonadIO m => Query -> Action m Document
- findAndModify :: (Applicative m, MonadIO m) => Query -> Document -> Action m (Either String Document)
- count :: MonadIO' m => Query -> Action m Int
- distinct :: MonadIO' m => Label -> Selection -> Action m [Value]
- data Cursor
- nextBatch :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m [Document]
- next :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m (Maybe Document)
- nextN :: (MonadIO m, MonadBaseControl IO m, Functor m) => Int -> Cursor -> Action m [Document]
- rest :: (MonadIO m, MonadBaseControl IO m, Functor m) => Cursor -> Action m [Document]
- closeCursor :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m ()
- isCursorClosed :: (MonadIO m, MonadBase IO m) => Cursor -> Action m Bool
- type Pipeline = [Document]
- aggregate :: MonadIO' m => Collection -> Pipeline -> Action 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 :: MonadIO' m => Group -> Action m [Document]
- data MapReduce = MapReduce {}
- type MapFun = Javascript
- type ReduceFun = Javascript
- type FinalizeFun = Javascript
- data MROut
- data MRMerge
- type MRResult = Document
- mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce
- runMR :: (MonadIO m, MonadBaseControl IO m, Applicative m) => MapReduce -> Action m Cursor
- runMR' :: MonadIO' m => MapReduce -> Action m MRResult
- type Command = Document
- runCommand :: MonadIO' m => Command -> Action m Document
- runCommand1 :: MonadIO' m => Text -> Action m Document
- eval :: (MonadIO' m, Val v) => Javascript -> Action m v
Monad
A monad on top of m (which must be a MonadIO) that may access the database and may fail with a DB Failure
MonadTrans Action | |
MonadTransControl Action | |
MonadBase b m => MonadBase b (Action m) | |
(MonadIO m, MonadBaseControl b m) => MonadBaseControl b (Action m) | |
Monad m => MonadError Failure (Action m) | |
Monad m => Monad (Action m) | |
Functor m => Functor (Action m) | |
(Monad m, Functor m) => Applicative (Action m) | |
MonadIO m => MonadIO (Action m) | |
(MonadBaseControl IO m, Applicative m, Functor m) => MonadDB (Action m) |
access :: MonadIO m => Pipe -> AccessMode -> Database -> Action m a -> m (Either Failure a)Source
Run action against database on server at other end of pipe. Use access mode for any reads and writes. Return Left on connection failure or read/write failure.
A connection failure, or a 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.
ConnectionFailure IOError | TCP connection ( |
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 ErrorCode 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 |
DocNotFound Selection |
|
AggregateFailure String |
|
data AccessMode Source
Type of reads and writes to perform
ReadStaleOk | Read-only action, reading stale data from a slave is OK. |
UnconfirmedWrites | Read-write action, slave not OK, every write is fire & forget. |
ConfirmWrites GetLastError | Read-write action, slave not OK, every write is confirmed with getLastError. |
type GetLastError = DocumentSource
Parameters for getLastError command. For example ["w" =: 2]
tells the server to wait for the write to reach at least two servers in replica set before acknowledging. See http://www.mongodb.org/display/DOCS/Last+Error+Commands for more options.
Same as ConfirmWrites
[]
Same as ReadStaleOk
accessMode :: Monad m => AccessMode -> Action m a -> Action m aSource
Run action with given AccessMode
class (Monad m, MonadBaseControl IO (BaseMonad m), Applicative (BaseMonad m), Functor (BaseMonad m)) => MonadDB m whereSource
Database
allDatabases :: MonadIO' m => Action m [Database]Source
List all databases residing on server
thisDatabase :: Monad m => Action m DatabaseSource
Current database in use
Authentication
auth :: MonadIO' m => Username -> Password -> Action m BoolSource
Authenticate with the current database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new pipe.
Collection
type Collection = TextSource
Collection name (not prefixed with database)
allCollections :: (MonadIO m, MonadBaseControl IO m, Functor m) => Action 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
Insert
insert :: MonadIO' m => Collection -> Document -> Action m ValueSource
Insert document into collection and return its "_id" value, which is created automatically if not supplied
insert_ :: MonadIO' m => Collection -> Document -> Action m ()Source
Same as insert
except don't return _id
insertMany :: MonadIO m => Collection -> [Document] -> Action m [Value]Source
Insert documents into collection and return their "_id" values, which are created automatically if not supplied. If a document fails to be inserted (eg. due to duplicate key) then remaining docs are aborted, and LastError is set.
insertMany_ :: MonadIO m => Collection -> [Document] -> Action m ()Source
Same as insertMany
except don't return _ids
insertAll :: MonadIO m => Collection -> [Document] -> Action m [Value]Source
Insert documents into collection and return their "_id" values, which are created automatically if not supplied. If a document fails to be inserted (eg. due to duplicate key) then remaining docs are still inserted. LastError is set if any doc fails, not just last one.
insertAll_ :: MonadIO m => Collection -> [Document] -> Action m ()Source
Same as insertAll
except don't return _ids
Update
save :: MonadIO' m => Collection -> Document -> Action 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 :: MonadIO m => Selection -> Document -> Action m ()Source
Replace first document in selection with given document
repsert :: MonadIO m => Selection -> Document -> Action 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 :: MonadIO m => Selection -> Modifier -> Action m ()Source
Update all documents in selection using given modifier
Delete
Read
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 | The server normally times out idle cursors after 10 minutes to prevent a memory leak in case a client forgets to close a cursor. Set this option to allow a cursor to live forever until it is closed. |
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.
| Exhaust -- ^ Stream the data down full blast in multiple more packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection.
Exhaust commented out because not compatible with current |
Partial | Get partial results from a _mongos_ if some shards are down, instead of throwing an error. |
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.
find :: (MonadIO m, MonadBaseControl IO m) => Query -> Action m CursorSource
Fetch documents satisfying query
findOne :: MonadIO m => Query -> Action m (Maybe Document)Source
Fetch first document satisfying query or Nothing if none satisfy it
fetch :: MonadIO m => Query -> Action m DocumentSource
Same as findOne
except throw DocNotFound
if none match
runs the findAndModify command. Returns a single updated document (new option is set to true). Currently this API does not allow setting the remove option
count :: MonadIO' m => Query -> Action m IntSource
Fetch number of documents satisfying query (including effect of skip and/or limit if present)
distinct :: MonadIO' m => Label -> Selection -> Action 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 pipe is closed, so you can open another pipe to the same server and continue using the cursor.
nextBatch :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m [Document]Source
Return next batch of documents in query result, which will be empty if finished.
next :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m (Maybe Document)Source
Return next document in query result, or Nothing if finished.
nextN :: (MonadIO m, MonadBaseControl IO m, Functor m) => Int -> Cursor -> Action m [Document]Source
Return next N documents or less if end is reached
rest :: (MonadIO m, MonadBaseControl IO m, Functor m) => Cursor -> Action m [Document]Source
Return remaining documents in query result
closeCursor :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m ()Source
Aggregate
aggregate :: MonadIO' m => Collection -> Pipeline -> Action m [Document]Source
Runs an aggregate and unpacks the result. See http://docs.mongodb.org/manual/core/aggregation/ for details.
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 :: MonadIO' m => Group -> Action 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 to a single result. There are additional parameters that may be set to tweak this basic operation. This implements the latest version of map-reduce that requires MongoDB 1.7.4 or greater. To map-reduce against an older server use runCommand directly as described in http:www.mongodb.orgdisplayDOCS/MapReduce.
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]) -> 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: reduce(k, [reduce(k,vs)]) == reduce(k,vs)
. 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.
type MRResult = DocumentSource
Result of running a MapReduce has some stats besides the output. See http:www.mongodb.orgdisplayDOCS/MapReduce#MapReduce-Resultobject
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 :: (MonadIO m, MonadBaseControl IO m, Applicative m) => MapReduce -> Action m CursorSource
Run MapReduce and return cursor of results. Error if map/reduce fails (because of bad Javascript)
runMR' :: MonadIO' m => MapReduce -> Action m MRResultSource
Run MapReduce and return a MR result document containing stats and the results if Inlined. 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.