-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | Driver (client) for MongoDB, a free, scalable, fast, document DBMS -- -- This package lets you connect to MongoDB servers and update/query -- their data. Please see the example in Database.MongoDB and the -- tutorial from the homepage. For information about MongoDB itself, see -- www.mongodb.org. @package mongoDB @version 2.0 -- | Pipelining is sending multiple requests over a socket and receiving -- the responses later in the same order (a' la HTTP pipelining). This is -- faster than sending one request, waiting for the response, then -- sending the next request, and so on. This implementation returns a -- promise (future) response for each request that when invoked -- waits for the response if not already arrived. Multiple threads can -- send on the same pipeline (and get promises back); it will send each -- thread's request right away without waiting. -- -- A pipeline closes itself when a read or write causes an error, so you -- can detect a broken pipeline by checking isClosed. It also closes -- itself when garbage collected, or you can close it explicitly. module System.IO.Pipeline -- | An IO sink and source where value of type o are sent and -- values of type i are received. data IOStream i o IOStream :: (o -> IO ()) -> IO i -> IO () -> IOStream i o writeStream :: IOStream i o -> o -> IO () readStream :: IOStream i o -> IO i closeStream :: IOStream i o -> IO () -- | Thread-safe and pipelined connection data Pipeline i o -- | Create new Pipeline over given handle. You should close -- pipeline when finished, which will also close handle. If pipeline is -- not closed but eventually garbage collected, it will be closed along -- with handle. newPipeline :: IOStream i o -> IO (Pipeline i o) -- | Send message to destination; the destination must not response -- (otherwise future calls will get these responses instead of -- their own). Throw IOError and close pipeline if send fails send :: Pipeline i o -> o -> IO () -- | Send message to destination and return promise of response from -- one message only. The destination must reply to the message (otherwise -- promises will have the wrong responses in them). Throw IOError and -- closes pipeline if send fails, likewise for promised response. call :: Pipeline i o -> o -> IO (IO i) -- | Close pipe and underlying connection close :: Pipeline i o -> IO () isClosed :: Pipeline i o -> IO Bool -- | Miscellaneous general functions and Show, Eq, and Ord instances for -- PortID module Database.MongoDB.Internal.Util -- | A monadic sort implementation derived from the non-monadic one in -- ghc's Prelude mergesortM :: Monad m => (a -> a -> m Ordering) -> [a] -> m [a] mergesortM' :: Monad m => (a -> a -> m Ordering) -> [[a]] -> m [a] merge_pairsM :: Monad m => (a -> a -> m Ordering) -> [[a]] -> m [[a]] mergeM :: Monad m => (a -> a -> m Ordering) -> [a] -> [a] -> m [a] wrap :: a -> [a] -- | Randomly shuffle items in list shuffle :: [a] -> IO [a] -- | Repeatedy execute action, collecting results, until it returns Nothing loop :: (Functor m, Monad m) => m (Maybe a) -> m [a] -- | Apply action to elements one at a time until one succeeds. Throw last -- error if all fail. Throw strMsg error if list is empty. untilSuccess :: (MonadError e m, Error e) => (a -> m b) -> [a] -> m b -- | Apply action to elements one at a time until one succeeds. Throw last -- error if all fail. Throw given error if list is empty untilSuccess' :: MonadError e m => e -> (a -> m b) -> [a] -> m b whenJust :: Monad m => Maybe a -> (a -> m ()) -> m () -- | lift IOE monad to ErrorT monad over some MonadIO m liftIOE :: (MonadIO m, Exception e, Exception e') => (e -> e') -> IO a -> m a -- | Change or insert value of key in association list updateAssocs :: Eq k => k -> v -> [(k, v)] -> [(k, v)] -- | bit-or all numbers together bitOr :: (Num a, Bits a) => [a] -> a -- | Concat first and second together with period in between. Eg. -- "hello" <.> "world" = "hello.world" (<.>) :: Text -> Text -> Text -- | Is field's value a 1 or True (MongoDB use both Int and Bools for truth -- values). Error if field not in document or field not a Num or Bool. true1 :: Label -> Document -> Bool -- | Read N bytes from hande, blocking until all N bytes are read. If EOF -- is reached before N bytes then raise EOF exception. hGetN :: Handle -> Int -> IO ByteString -- | Hexadecimal string representation of a byte string. Each byte yields -- two hexadecimal characters. byteStringHex :: ByteString -> String -- | Two char hexadecimal representation of byte byteHex :: Word8 -> String instance Ord PortID -- | Low-level messaging between this client and the MongoDB server, see -- Mongo Wire Protocol -- (http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol). -- -- This module is not intended for direct use. Use the high-level -- interface at Database.MongoDB.Query and -- Database.MongoDB.Connection instead. module Database.MongoDB.Internal.Protocol -- | Database name and collection name with period (.) in between. Eg. -- "myDb.myCollection" type FullCollection = Text -- | Thread-safe TCP connection with pipelined requests type Pipe = Pipeline Response Message -- | Create pipe over handle newPipe :: Handle -> IO Pipe -- | Send notices as a contiguous batch to server with no reply. Throw -- IOError if connection fails. send :: Pipe -> [Notice] -> IO () -- | Send notices and request as a contiguous batch to server and return -- reply promise, which will block when invoked until reply arrives. This -- call and resulting promise will throw IOError if connection fails. call :: Pipe -> [Notice] -> Request -> IO (IO Reply) -- | A notice is a message that is sent with no reply data Notice Insert :: FullCollection -> [InsertOption] -> [Document] -> Notice iFullCollection :: Notice -> FullCollection iOptions :: Notice -> [InsertOption] iDocuments :: Notice -> [Document] Update :: FullCollection -> [UpdateOption] -> Document -> Document -> Notice uFullCollection :: Notice -> FullCollection uOptions :: Notice -> [UpdateOption] uSelector :: Notice -> Document uUpdater :: Notice -> Document Delete :: FullCollection -> [DeleteOption] -> Document -> Notice dFullCollection :: Notice -> FullCollection dOptions :: Notice -> [DeleteOption] dSelector :: Notice -> Document KillCursors :: [CursorId] -> Notice kCursorIds :: Notice -> [CursorId] data InsertOption -- | If set, the database will not stop processing a bulk insert if one -- fails (eg due to duplicate IDs). This makes bulk insert behave -- similarly to a series of single inserts, except lastError will be set -- if any insert fails, not just the last one. (new in 1.9.1) KeepGoing :: InsertOption data UpdateOption -- | If set, the database will insert the supplied object into the -- collection if no matching document is found Upsert :: UpdateOption -- | If set, the database will update all matching objects in the -- collection. Otherwise only updates first matching doc MultiUpdate :: UpdateOption data DeleteOption -- | If set, the database will remove only the first matching document in -- the collection. Otherwise all matching documents will be removed SingleRemove :: DeleteOption type CursorId = Int64 -- | A request is a message that is sent with a Reply expected in -- return data Request Query :: [QueryOption] -> FullCollection -> Int32 -> Int32 -> Document -> Document -> Request qOptions :: Request -> [QueryOption] qFullCollection :: Request -> FullCollection -- | Number of initial matching documents to skip qSkip :: Request -> Int32 -- | The number of document to return in each batch response from the -- server. 0 means use Mongo default. Negative means close cursor after -- first batch and use absolute value as batch size. qBatchSize :: Request -> Int32 -- | [] = return all documents in collection qSelector :: Request -> Document -- | [] = return whole document qProjector :: Request -> Document GetMore :: FullCollection -> Int32 -> CursorId -> Request gFullCollection :: Request -> FullCollection gBatchSize :: Request -> Int32 gCursorId :: Request -> CursorId data QueryOption -- | 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. TailableCursor :: QueryOption -- | Allow query of replica slave. Normally these return an error except -- for namespace local. SlaveOK :: QueryOption -- | 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. NoCursorTimeout :: QueryOption -- | 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 Pipeline -- implementation AwaitData :: QueryOption -- | Get partial results from a _mongos_ if some shards are down, instead -- of throwing an error. Partial :: QueryOption -- | A reply is a message received in response to a Request data Reply Reply :: [ResponseFlag] -> CursorId -> Int32 -> [Document] -> Reply rResponseFlags :: Reply -> [ResponseFlag] -- | 0 = cursor finished rCursorId :: Reply -> CursorId rStartingFrom :: Reply -> Int32 rDocuments :: Reply -> [Document] data ResponseFlag -- | Set when getMore is called but the cursor id is not valid at the -- server. Returned with zero results. CursorNotFound :: ResponseFlag -- | Query error. Returned with one document containing an $err -- field holding the error message. QueryError :: ResponseFlag -- | For backward compatability: Set when the server supports the AwaitData -- query option. if it doesn't, a replica slave client should sleep a -- little between getMore's AwaitCapable :: ResponseFlag type Username = Text type Password = Text type Nonce = Text pwHash :: Username -> Password -> Text pwKey :: Nonce -> Username -> Password -> Text instance Show InsertOption instance Eq InsertOption instance Show UpdateOption instance Eq UpdateOption instance Show DeleteOption instance Eq DeleteOption instance Show Notice instance Eq Notice instance Show QueryOption instance Eq QueryOption instance Show Request instance Eq Request instance Show ResponseFlag instance Eq ResponseFlag instance Enum ResponseFlag instance Show Reply instance Eq Reply -- | Query and update documents module Database.MongoDB.Query -- | A monad on top of m (which must be a MonadIO) that may access the -- database and may fail with a DB Failure type Action = ReaderT MongoContext -- | 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. access :: MonadIO m => Pipe -> AccessMode -> Database -> Action m a -> m a -- | 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. data Failure -- | TCP connection (Pipeline) failed. May work if you try again on -- the same Mongo Connection which will create a new Pipe. ConnectionFailure :: IOError -> Failure -- | 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) CursorNotFoundFailure :: CursorId -> Failure -- | Query failed for some reason as described in the string QueryFailure :: ErrorCode -> String -> Failure -- | Error observed by getLastError after a write, error description is in -- string WriteFailure :: ErrorCode -> String -> Failure -- | fetch found no document matching selection DocNotFound :: Selection -> Failure -- | aggregate returned an error AggregateFailure :: String -> Failure -- | Error code from getLastError or query failure type ErrorCode = Int -- | Type of reads and writes to perform data AccessMode -- | Read-only action, reading stale data from a slave is OK. ReadStaleOk :: AccessMode -- | Read-write action, slave not OK, every write is fire & forget. UnconfirmedWrites :: AccessMode -- | Read-write action, slave not OK, every write is confirmed with -- getLastError. ConfirmWrites :: GetLastError -> AccessMode -- | 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. type GetLastError = Document -- | Same as ConfirmWrites [] master :: AccessMode -- | Same as ReadStaleOk slaveOk :: AccessMode -- | Run action with given AccessMode accessMode :: Monad m => AccessMode -> Action m a -> Action m a liftDB :: (MonadReader env m, HasMongoContext env, MonadIO m) => Action IO a -> m a -- | Values needed when executing a db operation data MongoContext class HasMongoContext env mongoContext :: HasMongoContext env => env -> MongoContext type Database = Text -- | List all databases residing on server allDatabases :: MonadIO m => Action m [Database] -- | Run action against given database useDb :: Monad m => Database -> Action m a -> Action m a -- | Current database in use thisDatabase :: Monad m => Action m Database type Username = Text type Password = Text -- | 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. auth :: MonadIO m => Username -> Password -> Action m Bool -- | Collection name (not prefixed with database) type Collection = Text -- | List all collections in this database allCollections :: (MonadIO m, MonadBaseControl IO m) => Action m [Collection] -- | Selects documents in collection that match selector data Selection Select :: Selector -> Collection -> Selection selector :: Selection -> Selector coll :: Selection -> Collection -- | 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. type Selector = Document -- | Add Javascript predicate to selector, in which case a document must -- match both selector and predicate whereJS :: Selector -> Javascript -> Selector class Select aQueryOrSelection select :: Select aQueryOrSelection => Selector -> Collection -> aQueryOrSelection -- | Insert document into collection and return its "_id" value, which is -- created automatically if not supplied insert :: MonadIO m => Collection -> Document -> Action m Value -- | Same as insert except don't return _id insert_ :: MonadIO m => Collection -> Document -> Action m () -- | 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 [Value] -- | Same as insertMany except don't return _ids insertMany_ :: MonadIO m => Collection -> [Document] -> Action m () -- | 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 [Value] -- | Same as insertAll except don't return _ids insertAll_ :: MonadIO m => Collection -> [Document] -> Action m () -- | Save document to collection, meaning insert it if its new (has no -- "_id" field) or update it if its not new (has "_id" field) save :: MonadIO m => Collection -> Document -> Action m () -- | Replace first document in selection with given document replace :: MonadIO m => Selection -> Document -> Action m () -- | Replace first document in selection with given document, or insert -- document if selection is empty repsert :: MonadIO m => Selection -> Document -> Action m () -- | Update operations on fields in a document. See -- http://www.mongodb.org/display/DOCS/Updating#Updating-ModifierOperations type Modifier = Document -- | Update all documents in selection using given modifier modify :: MonadIO m => Selection -> Modifier -> Action m () -- | Delete all documents in selection delete :: MonadIO m => Selection -> Action m () -- | Delete first document in selection deleteOne :: MonadIO m => Selection -> Action m () -- | Use select to create a basic query with defaults, then modify -- if desired. For example, (select sel col) {limit = 10} data Query Query :: [QueryOption] -> Selection -> Projector -> Word32 -> Limit -> Order -> Bool -> BatchSize -> Order -> Query -- | Default = [] options :: Query -> [QueryOption] selection :: Query -> Selection -- | [] = all fields. Default = [] project :: Query -> Projector -- | Number of initial matching documents to skip. Default = 0 skip :: Query -> Word32 -- | Maximum number of documents to return, 0 = no limit. Default = 0 limit :: Query -> Limit -- | Sort results by this order, [] = no sort. Default = [] sort :: Query -> Order -- | If true assures no duplicates are returned, or objects missed, which -- were present at both the start and end of the query's execution (even -- if the object were updated). If an object is new during the query, or -- deleted during the query, it may or may not be returned, even with -- snapshot mode. Note that short query responses (less than 1MB) are -- always effectively snapshotted. Default = False snapshot :: Query -> Bool -- | The number of document to return in each batch response from the -- server. 0 means use Mongo default. Default = 0 batchSize :: Query -> BatchSize -- | Force MongoDB to use this index, [] = no hint. Default = [] hint :: Query -> Order data QueryOption -- | 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. TailableCursor :: QueryOption -- | 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. NoCursorTimeout :: QueryOption -- | 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 Pipeline -- implementation AwaitData :: QueryOption -- | Get partial results from a _mongos_ if some shards are down, instead -- of throwing an error. Partial :: QueryOption -- | 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. type Projector = Document -- | Maximum number of documents to return, i.e. cursor will close after -- iterating over this number of documents. 0 means no limit. type Limit = Word32 -- | 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 type Order = Document -- | The number of document to return in each batch response from the -- server. 0 means use Mongo default. type BatchSize = Word32 -- | Return performance stats of query execution explain :: MonadIO m => Query -> Action m Document -- | Fetch documents satisfying query find :: (MonadIO m, MonadBaseControl IO m) => Query -> Action m Cursor -- | Fetch first document satisfying query or Nothing if none satisfy it findOne :: MonadIO m => Query -> Action m (Maybe Document) -- | Same as findOne except throw DocNotFound if none match fetch :: MonadIO m => Query -> Action m Document -- | 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 findAndModify :: MonadIO m => Query -> Document -> Action m (Either String Document) -- | Fetch number of documents satisfying query (including effect of skip -- and/or limit if present) count :: MonadIO m => Query -> Action m Int -- | Fetch distinct values of field in selected documents distinct :: MonadIO m => Label -> Selection -> Action m [Value] -- | 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. data Cursor -- | Return next batch of documents in query result, which will be empty if -- finished. nextBatch :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m [Document] -- | Return next document in query result, or Nothing if finished. next :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m (Maybe Document) -- | Return next N documents or less if end is reached nextN :: (MonadIO m, MonadBaseControl IO m) => Int -> Cursor -> Action m [Document] -- | Return remaining documents in query result rest :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m [Document] closeCursor :: (MonadIO m, MonadBaseControl IO m) => Cursor -> Action m () isCursorClosed :: (MonadIO m, MonadBase IO m) => Cursor -> Action m Bool -- | The Aggregate Pipeline type Pipeline = [Document] -- | Runs an aggregate and unpacks the result. See -- http://docs.mongodb.org/manual/core/aggregation/ for details. aggregate :: MonadIO m => Collection -> Pipeline -> Action m [Document] -- | Groups documents in collection by key then reduces (aggregates) each -- group data Group Group :: Collection -> GroupKey -> Javascript -> Document -> Selector -> Maybe Javascript -> Group gColl :: Group -> Collection -- | Fields to group by gKey :: Group -> GroupKey -- | (doc, agg) -> (). The reduce function reduces (aggregates) -- the objects iterated. Typical operations of a reduce function include -- summing and counting. It takes two arguments, the current document -- being iterated over and the aggregation value, and updates the -- aggregate value. gReduce :: Group -> Javascript -- | agg. Initial aggregation value supplied to reduce gInitial :: Group -> Document -- | Condition that must be true for a row to be considered. [] means -- always true. gCond :: Group -> Selector -- | agg -> () | result. An optional function to be run on each -- item in the result set just before the item is returned. Can either -- modify the item (e.g., add an average field given a count and a total) -- or return a replacement object (returning a new object with just _id -- and average fields). gFinalize :: Group -> Maybe Javascript -- | 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). data GroupKey Key :: [Label] -> GroupKey KeyF :: Javascript -> GroupKey -- | Execute group query and return resulting aggregate value for each -- distinct key group :: MonadIO m => Group -> Action m [Document] -- | 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. data MapReduce MapReduce :: Collection -> MapFun -> ReduceFun -> Selector -> Order -> Limit -> MROut -> Maybe FinalizeFun -> Document -> Bool -> MapReduce rColl :: MapReduce -> Collection rMap :: MapReduce -> MapFun rReduce :: MapReduce -> ReduceFun -- | Operate on only those documents selected. Default is [] meaning all -- documents. rSelect :: MapReduce -> Selector -- | Default is [] meaning no sort rSort :: MapReduce -> Order -- | Default is 0 meaning no limit rLimit :: MapReduce -> Limit -- | Output to a collection with a certain merge policy. Default is no -- collection (Inline). Note, you don't want this default if your -- result set is large. rOut :: MapReduce -> MROut -- | Function to apply to all the results when finished. Default is -- Nothing. rFinalize :: MapReduce -> Maybe FinalizeFun -- | Variables (environment) that can be accessed from -- mapreducefinalize. Default is []. rScope :: MapReduce -> Document -- | Provide statistics on job execution time. Default is False. rVerbose :: MapReduce -> Bool -- | () -> 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 MapFun = Javascript -- | (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 ReduceFun = Javascript -- | (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 FinalizeFun = Javascript data MROut -- | Return results directly instead of writing them to an output -- collection. Results must fit within 16MB limit of a single document Inline :: MROut -- | Write results to given collection, in other database if specified. -- Follow merge policy when entry already exists Output :: MRMerge -> Collection -> (Maybe Database) -> MROut data MRMerge -- | Clear all old data and replace it with new data Replace :: MRMerge -- | Leave old data but overwrite entries with the same key with new data Merge :: MRMerge -- | Leave old data but combine entries with the same key via MR's reduce -- function Reduce :: MRMerge -- | Result of running a MapReduce has some stats besides the output. See -- http:www.mongodb.orgdisplayDOCS/MapReduce#MapReduce-Resultobject type MRResult = Document -- | MapReduce on collection with given map and reduce functions. Remaining -- attributes are set to their defaults, which are stated in their -- comments. mapReduce :: Collection -> MapFun -> ReduceFun -> MapReduce -- | Run MapReduce and return cursor of results. Error if map/reduce fails -- (because of bad Javascript) runMR :: (MonadIO m, MonadBaseControl IO m) => MapReduce -> Action m Cursor -- | 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). runMR' :: MonadIO m => MapReduce -> Action m MRResult -- | A command is a special query or action against the database. See -- http://www.mongodb.org/display/DOCS/Commands for details. type Command = Document -- | Run command against the database and return its result runCommand :: MonadIO m => Command -> Action m Document -- |
--   runCommand1 foo = runCommand [foo =: 1]
--   
runCommand1 :: MonadIO m => Text -> Action m Document -- | Run code on server eval :: (MonadIO m, Val v) => Javascript -> Action m v instance Typeable Failure instance Show AccessMode instance Show Selection instance Eq Selection instance Show Failure instance Eq Failure instance Show WriteMode instance Eq WriteMode instance Show ReadMode instance Eq ReadMode instance Show Query instance Eq Query instance Show GroupKey instance Eq GroupKey instance Show Group instance Eq Group instance Show MRMerge instance Eq MRMerge instance Show MROut instance Eq MROut instance Show MapReduce instance Eq MapReduce instance Select Query instance Select Selection instance HasMongoContext MongoContext instance Error Failure instance Exception Failure -- | Connect to a single server or a replica set of servers module Database.MongoDB.Connection type Secs = Double -- | Thread-safe TCP connection with pipelined requests type Pipe = Pipeline Response Message -- | Close pipe and underlying connection close :: Pipeline i o -> IO () isClosed :: Pipeline i o -> IO Bool data Host Host :: HostName -> PortID -> Host data PortID :: * Service :: String -> PortID PortNumber :: PortNumber -> PortID UnixSocket :: String -> PortID -- | Default MongoDB port = 27017 defaultPort :: PortID -- | Host on defaultPort host :: HostName -> Host -- | Display host as "host:port" TODO: Distinguish Service and UnixSocket -- port showHostPort :: Host -> String -- | Read string "hostname:port" as Host hostname (PortNumber -- port) or "hostname" as host hostname (default port). -- Error if string does not match either syntax. readHostPort :: String -> Host -- | Read string "hostname:port" as Host hosthame (PortNumber -- port) or "hostname" as host hostname (default port). -- Fail if string does not match either syntax. TODO: handle Service and -- UnixSocket port readHostPortM :: Monad m => String -> m Host -- | connect (and openReplicaSet) fails if it can't connect -- within this many seconds (default is 6 seconds). Use 'connect\'' (and -- 'openReplicaSet\'') if you want to ignore this global and specify your -- own timeout. Note, this timeout only applies to initial connection -- establishment, not when reading/writing to the connection. globalConnectTimeout :: IORef Secs -- | Connect to Host returning pipelined TCP connection. Throw IOError if -- connection refused or no response within globalConnectTimeout. connect :: Host -> IO Pipe -- | Connect to Host returning pipelined TCP connection. Throw IOError if -- connection refused or no response within given number of seconds. connect' :: Secs -> Host -> IO Pipe type ReplicaSetName = Text -- | Open connections (on demand) to servers in replica set. Supplied hosts -- is seed list. At least one of them must be a live member of the named -- replica set, otherwise fail. The value of globalConnectTimeout -- at the time of this call is the timeout used for future member connect -- attempts. To use your own value call 'openReplicaSet\'' instead. openReplicaSet :: (ReplicaSetName, [Host]) -> IO ReplicaSet -- | Open connections (on demand) to servers in replica set. Supplied hosts -- is seed list. At least one of them must be a live member of the named -- replica set, otherwise fail. Supplied seconds timeout is used for -- connect attempts to members. openReplicaSet' :: Secs -> (ReplicaSetName, [Host]) -> IO ReplicaSet -- | Maintains a connection (created on demand) to each server in the named -- replica set data ReplicaSet -- | Return connection to current primary of replica set. Fail if no -- primary available. primary :: ReplicaSet -> IO Pipe -- | Return connection to a random secondary, or primary if no secondaries -- available. secondaryOk :: ReplicaSet -> IO Pipe -- | Return a connection to a host using a user-supplied sorting function, -- which sorts based on a tuple containing the host and a boolean -- indicating whether the host is primary. routedHost :: ((Host, Bool) -> (Host, Bool) -> IO Ordering) -> ReplicaSet -> IO Pipe -- | Close all connections to replica set closeReplicaSet :: ReplicaSet -> IO () -- | name of connected replica set replSetName :: ReplicaSet -> Text instance Show Host instance Eq Host instance Ord Host -- | Database administrative functions module Database.MongoDB.Admin data CollectionOption Capped :: CollectionOption MaxByteSize :: Int -> CollectionOption MaxItems :: Int -> CollectionOption -- | Create collection with given options. You only need to call this to -- set options, otherwise a collection is created automatically on first -- use with no options. createCollection :: MonadIO m => [CollectionOption] -> Collection -> Action m Document -- | Rename first collection to second collection renameCollection :: MonadIO m => Collection -> Collection -> Action m Document -- | Delete the given collection! Return True if collection existed (and -- was deleted); return False if collection did not exist (and no -- action). dropCollection :: MonadIO m => Collection -> Action m Bool -- | This operation takes a while validateCollection :: MonadIO m => Collection -> Action m Document data Index Index :: Collection -> Order -> IndexName -> Bool -> Bool -> Index iColl :: Index -> Collection iKey :: Index -> Order iName :: Index -> IndexName iUnique :: Index -> Bool iDropDups :: Index -> Bool type IndexName = Text -- | Spec of index of ordered keys on collection. Name is generated from -- keys. Unique and dropDups are False. index :: Collection -> Order -> Index -- | Create index if we did not already create one. May be called -- repeatedly with practically no performance hit, because we remember if -- we already called this for the same index (although this memory gets -- wiped out every 15 minutes, in case another client drops the index and -- we want to create it again). ensureIndex :: MonadIO m => Index -> Action m () -- | Create index on the server. This call goes to the server every time. createIndex :: MonadIO m => Index -> Action m () -- | Remove the index dropIndex :: MonadIO m => Collection -> IndexName -> Action m Document -- | Get all indexes on this collection getIndexes :: (MonadIO m, MonadBaseControl IO m, Functor m) => Collection -> Action m [Document] -- | Drop all indexes on this collection dropIndexes :: MonadIO m => Collection -> Action m Document -- | Fetch all users of this database allUsers :: (MonadIO m, MonadBaseControl IO m, Functor m) => Action m [Document] -- | Add user with password with read-only access if bool is True or -- read-write access if bool is False addUser :: MonadIO m => Bool -> Username -> Password -> Action m () removeUser :: MonadIO m => Username -> Action m () -- | "admin" database admin :: Database -- | Copy database from given host to the server I am connected to. Fails -- and returns ok = 0 if we don't have permission to read -- from given server (use copyDatabase in this case). cloneDatabase :: MonadIO m => Database -> Host -> Action m Document -- | Copy database from given host to the server I am connected to. If -- username & password is supplied use them to read from given host. copyDatabase :: MonadIO m => Database -> Host -> Maybe (Username, Password) -> Database -> Action m Document -- | Delete the given database! dropDatabase :: MonadIO m => Database -> Action m Document -- | Attempt to fix any corrupt records. This operation takes a while. repairDatabase :: MonadIO m => Database -> Action m Document serverBuildInfo :: MonadIO m => Action m Document serverVersion :: MonadIO m => Action m Text collectionStats :: MonadIO m => Collection -> Action m Document dataSize :: MonadIO m => Collection -> Action m Int storageSize :: MonadIO m => Collection -> Action m Int totalIndexSize :: MonadIO m => Collection -> Action m Int totalSize :: (MonadIO m, MonadBaseControl IO m) => Collection -> Action m Int data ProfilingLevel Off :: ProfilingLevel Slow :: ProfilingLevel All :: ProfilingLevel getProfilingLevel :: MonadIO m => Action m ProfilingLevel type MilliSec = Int setProfilingLevel :: MonadIO m => ProfilingLevel -> Maybe MilliSec -> Action m () dbStats :: MonadIO m => Action m Document type OpNum = Int -- | See currently running operation on the database, if any currentOp :: MonadIO m => Action m (Maybe Document) killOp :: MonadIO m => OpNum -> Action m (Maybe Document) serverStatus :: MonadIO m => Action m Document instance Show CollectionOption instance Eq CollectionOption instance Show Index instance Eq Index instance Show ProfilingLevel instance Enum ProfilingLevel instance Eq ProfilingLevel -- | Client interface to MongoDB database management system. -- -- Simple example below. Use with language extensions -- OvererloadedStrings & ExtendedDefaultRules. -- --
--   
--   
--   import Database.MongoDB
--   import Control.Monad.Trans (liftIO)
--   
--   main = do
--      pipe <- runIOE $ connect (host "127.0.0.1")
--      e <- access pipe master "baseball" run
--      close pipe
--      print e
--   
--   run = do
--      clearTeams
--      insertTeams
--      allTeams >>= printDocs "All Teams"
--      nationalLeagueTeams >>= printDocs "National League Teams"
--      newYorkTeams >>= printDocs "New York Teams"
--   
--   clearTeams = delete (select [] "team")
--   
--   insertTeams = insertMany "team" [
--      ["name" =: "Yankees", "home" =: ["city" =: "New York", "state" =: "NY"], "league" =: "American"],
--      ["name" =: "Mets", "home" =: ["city" =: "New York", "state" =: "NY"], "league" =: "National"],
--      ["name" =: "Phillies", "home" =: ["city" =: "Philadelphia", "state" =: "PA"], "league" =: "National"],
--      ["name" =: "Red Sox", "home" =: ["city" =: "Boston", "state" =: "MA"], "league" =: "American"] ]
--   
--   allTeams = rest =<< find (select [] "team") {sort = ["home.city" =: 1]}
--   
--   nationalLeagueTeams = rest =<< find (select ["league" =: "National"] "team")
--   
--   newYorkTeams = rest =<< find (select ["home.state" =: "NY"] "team") {project = ["name" =: 1, "league" =: 1]}
--   
--   printDocs title docs = liftIO $ putStrLn title >> mapM_ (print . exclude ["_id"]) docs
--   
module Database.MongoDB