A driver for MongoDB
This module lets you connect to MongoDB, do inserts, queries, updates, etc. Also has many convience functions inspired by HDBC such as more easily converting between the BsonValue types and native Haskell types.
- Tutorial for this driver: http://github.com/srp/mongoDB/blob/master/tutorial.md
- Map/Reduce example for this driver: http://github.com/srp/mongoDB/blob/master/map-reduce-example.md
- MongoDB: http://www.mongodb.org/
- data Connection
- data ConnectOpt = SlaveOK
- connect :: HostName -> [ConnectOpt] -> IO Connection
- connectOnPort :: HostName -> PortID -> [ConnectOpt] -> IO Connection
- conClose :: Connection -> IO ()
- disconnect :: Connection -> IO ()
- dropDatabase :: Connection -> Database -> IO ()
- connectCluster :: [HostName] -> [ConnectOpt] -> IO Connection
- connectClusterOnPort :: [(HostName, PortID)] -> [ConnectOpt] -> IO Connection
- serverInfo :: Connection -> IO BsonDoc
- serverShutdown :: Connection -> IO BsonDoc
- databasesInfo :: Connection -> IO BsonDoc
- databaseNames :: Connection -> IO [Database]
- type Database = ByteString
- data MongoDBCollectionInvalid
- type Password = String
- type Username = String
- data ColCreateOpt
- collectionNames :: Connection -> Database -> IO [FullCollection]
- createCollection :: Connection -> FullCollection -> [ColCreateOpt] -> IO ()
- dropCollection :: Connection -> FullCollection -> IO ()
- renameCollection :: Connection -> FullCollection -> FullCollection -> IO ()
- runCommand :: Connection -> Database -> BsonDoc -> IO BsonDoc
- validateCollection :: Connection -> FullCollection -> IO String
- auth :: Connection -> Database -> Username -> Password -> IO BsonDoc
- addUser :: Connection -> Database -> Username -> Password -> IO BsonDoc
- login :: Connection -> Database -> Username -> Password -> IO BsonDoc
- logout :: Connection -> Database -> IO ()
- type Collection = ByteString
- type FieldSelector = [ByteString]
- type FullCollection = ByteString
- type NumToSkip = Int32
- type NumToReturn = Int32
- type Selector = BsonDoc
- data QueryOpt
- data UpdateFlag
- count :: Connection -> FullCollection -> IO Integer
- countMatching :: Connection -> FullCollection -> Selector -> IO Integer
- delete :: Connection -> FullCollection -> Selector -> IO RequestID
- insert :: Connection -> FullCollection -> BsonDoc -> IO BsonValue
- insertMany :: Connection -> FullCollection -> [BsonDoc] -> IO [BsonValue]
- query :: Connection -> FullCollection -> [QueryOpt] -> NumToSkip -> NumToReturn -> Selector -> FieldSelector -> IO Cursor
- remove :: Connection -> FullCollection -> Selector -> IO RequestID
- update :: Connection -> FullCollection -> [UpdateFlag] -> Selector -> BsonDoc -> IO RequestID
- save :: Connection -> FullCollection -> BsonDoc -> IO BsonValue
- find :: Connection -> FullCollection -> Selector -> IO Cursor
- findOne :: Connection -> FullCollection -> Selector -> IO (Maybe BsonDoc)
- quickFind :: Connection -> FullCollection -> Selector -> IO [BsonDoc]
- quickFind' :: Connection -> FullCollection -> Selector -> IO [BsonDoc]
- whereClause :: String -> Maybe BsonDoc -> BsonDoc
- data Cursor
- allDocs :: Cursor -> IO [BsonDoc]
- allDocs' :: Cursor -> IO [BsonDoc]
- finish :: Cursor -> IO ()
- nextDoc :: Cursor -> IO (Maybe BsonDoc)
- type Key = ByteString
- type Unique = Bool
- data Direction
- = Ascending
- | Descending
- createIndex :: Connection -> FullCollection -> [(Key, Direction)] -> Unique -> IO ByteString
- dropIndex :: Connection -> FullCollection -> [(Key, Direction)] -> IO ()
- dropIndexes :: Connection -> FullCollection -> IO ()
- indexInformation :: Connection -> FullCollection -> IO [BsonDoc]
- data MapReduceOpt
- = MROptQuery BsonDoc
- | MROptLimit Int64
- | MROptOut ByteString
- | MROptKeepTemp
- | MROptFinalize JSCode
- | MROptScope BsonDoc
- | MROptVerbose
- mapReduce :: Connection -> FullCollection -> JSCode -> JSCode -> [MapReduceOpt] -> IO Cursor
- mapReduceWScopes :: Connection -> FullCollection -> JSCode -> BsonDoc -> JSCode -> BsonDoc -> [MapReduceOpt] -> IO Cursor
- runMapReduce :: Connection -> FullCollection -> JSCode -> JSCode -> [MapReduceOpt] -> IO BsonDoc
- runMapReduceWScopes :: Connection -> FullCollection -> JSCode -> BsonDoc -> JSCode -> BsonDoc -> [MapReduceOpt] -> IO BsonDoc
- mapReduceResults :: Connection -> Database -> BsonDoc -> IO Cursor
Connection
data Connection Source
A list of handles to database connections
connect :: HostName -> [ConnectOpt] -> IO ConnectionSource
Establish a connection to a MongoDB server
connectOnPort :: HostName -> PortID -> [ConnectOpt] -> IO ConnectionSource
Establish a connection to a MongoDB server on a non-standard port
conClose :: Connection -> IO ()Source
Close database connection
disconnect :: Connection -> IO ()Source
Alias for conClose
dropDatabase :: Connection -> Database -> IO ()Source
Drop a database.
connectCluster :: [HostName] -> [ConnectOpt] -> IO ConnectionSource
Establish connections to a list of MongoDB servers
connectClusterOnPort :: [(HostName, PortID)] -> [ConnectOpt] -> IO ConnectionSource
Establish connections to a list of MongoDB servers specifying each port.
serverInfo :: Connection -> IO BsonDocSource
Get information about the MongoDB server we're connected to.
serverShutdown :: Connection -> IO BsonDocSource
Shut down the MongoDB server.
Force a clean exit, flushing and closing all data files. Note that it will wait until all ongoing operations are complete.
databasesInfo :: Connection -> IO BsonDocSource
Information about the databases on the server.
databaseNames :: Connection -> IO [Database]Source
Return a list of database names on the server.
Database
type Database = ByteStringSource
The name of a database.
data ColCreateOpt Source
collectionNames :: Connection -> Database -> IO [FullCollection]Source
Return a list of collections in Database.
createCollection :: Connection -> FullCollection -> [ColCreateOpt] -> IO ()Source
Create a new collection in this database.
Normally collection creation is automatic. This function should
only be needed if you want to specify ColCreateOpt
s on creation.
MongoDBCollectionInvalid
is thrown if the collection already
exists.
dropCollection :: Connection -> FullCollection -> IO ()Source
Drop a collection.
renameCollection :: Connection -> FullCollection -> FullCollection -> IO ()Source
Rename a collection--first FullCollection argument is the existing name, the second is the new name. At the moment this command can also be used to move a collection between databases.
runCommand :: Connection -> Database -> BsonDoc -> IO BsonDocSource
Run a database command. Usually this is unneeded as driver wraps
all of the commands for you (eg createCollection
,
dropCollection
, etc).
validateCollection :: Connection -> FullCollection -> IO StringSource
Return a string of validation info about the collection.
Example output (note this probably can/will change with different versions of the server):
validate details: 0x7fe5cc2c1da4 ofs:e7da4 firstExtent:0:24100 ns:test.foo.bar lastExtent:0:24100 ns:test.foo.bar # extents:1 datasize?:180 nrecords?:5 lastExtentSize:1024 padding:1 first extent: loc:0:24100 xnext:null xprev:null nsdiag:test.foo.bar size:1024 firstRecord:0:241e4 lastRecord:0:24280 5 objects found, nobj:5 260 bytes data w/headers 180 bytes data wout/headers deletedList: 0100100000000000000 deleted: n: 4 size: 588 nIndexes:1 test.foo.bar.$_id_ keys:5
addUser :: Connection -> Database -> Username -> Password -> IO BsonDocSource
create a new user in the current Database
login :: Connection -> Database -> Username -> Password -> IO BsonDocSource
log into the mongodb Database attached to the Connection
Collection
type Collection = ByteStringSource
The same as FullCollection
but without the Database
prefix.
type FieldSelector = [ByteString]Source
A list of field names that limits the fields in the returned documents. The list can contains zero or more elements, each of which is the name of a field that should be returned. An empty list means that no limiting is done and all fields are returned.
type FullCollection = ByteStringSource
The full collection name. The full collection name is the
concatenation of the database name with the collection name, using
a .
for the concatenation. For example, for the database foo
and the collection bar
, the full collection name is foo.bar
.
Sets the number of documents to omit - starting from the first document in the resulting dataset - when returning the result of the query.
type NumToReturn = Int32Source
This controls how many documents are returned at a time. The cursor works by requesting NumToReturn documents, which are then immediately all transfered over the network; these are held locally until the those NumToReturn are all consumed and then the network will be hit again for the next NumToReturn documents.
If the value 0
is given, the database will choose the number of
documents to return.
Otherwise choosing a good value is very dependant on the document size and the way the cursor is being used.
A BsonDoc
representing restrictions for a query much like the
where part of an SQL query.
Options that control the behavior of a query
operation.
data UpdateFlag Source
Options that effect the behavior of a update
operation.
count :: Connection -> FullCollection -> IO IntegerSource
Return the number of documents in FullCollection.
countMatching :: Connection -> FullCollection -> Selector -> IO IntegerSource
Return the number of documents in FullCollection matching Selector
delete :: Connection -> FullCollection -> Selector -> IO RequestIDSource
Delete documents matching Selector from the given FullCollection.
insert :: Connection -> FullCollection -> BsonDoc -> IO BsonValueSource
Insert a single document into FullCollection returning the _id field.
insertMany :: Connection -> FullCollection -> [BsonDoc] -> IO [BsonValue]Source
Insert a list of documents into FullCollection returing the _id field for each one in the same order as they were given.
query :: Connection -> FullCollection -> [QueryOpt] -> NumToSkip -> NumToReturn -> Selector -> FieldSelector -> IO CursorSource
Open a cursor to find documents in FullCollection that match Selector. See the documentation for each argument's type for information about how it effects the query.
remove :: Connection -> FullCollection -> Selector -> IO RequestIDSource
An alias for delete
.
update :: Connection -> FullCollection -> [UpdateFlag] -> Selector -> BsonDoc -> IO RequestIDSource
Update documents with BsonDoc in FullCollection that match Selector.
save :: Connection -> FullCollection -> BsonDoc -> IO BsonValueSource
Conveniently stores the BsonDoc to the FullCollection if there is an _id present in the BsonDoc then it already has a place in the DB, so we update it using the _id, otherwise we insert it
Convenience collection operations
find :: Connection -> FullCollection -> Selector -> IO CursorSource
Open a cursor to find documents. If you need full functionality,
see query
findOne :: Connection -> FullCollection -> Selector -> IO (Maybe BsonDoc)Source
Query, but only return the first result, if any.
quickFind :: Connection -> FullCollection -> Selector -> IO [BsonDoc]Source
Perform a query and return the result as a lazy list. Be sure to
understand the comments about using the lazy list given for
allDocs
.
quickFind' :: Connection -> FullCollection -> Selector -> IO [BsonDoc]Source
Perform a query and return the result as a strict list.
Query Helpers
whereClause :: String -> Maybe BsonDoc -> BsonDocSource
Use this in the place of the query portion of a select type query This uses javascript and a scope supplied by a BsonDoc to evaluate documents in the database for retrieval.
Example:
findOne conn mycoll $ whereClause "this.name == (name1 + name2)" Just (toBsonDoc [("name1", toBson "mar"), ("name2", toBson "tha")])
Cursor
allDocs :: Cursor -> IO [BsonDoc]Source
Return a lazy list of all (of the rest) of the documents in the cursor. This works much like hGetContents--it will lazily read the cursor data out of the database as the list is used. The cursor is automatically closed when the list has been fully read.
If you manually finish the cursor before consuming off this list you won't get all the original documents in the cursor.
If you don't consume to the end of the list, you must manually close the cursor or you will leak the cursor, which may also leak on the database side.
allDocs' :: Cursor -> IO [BsonDoc]Source
Returns a strict list of all (of the rest) of the documents in the cursor. This means that all of the documents will immediately be read out of the database and loaded into memory.
nextDoc :: Cursor -> IO (Maybe BsonDoc)Source
Return one document or Nothing if there are no more. Automatically closes the cursor when last document is read
Index
type Key = ByteStringSource
The field key to index on.
createIndex :: Connection -> FullCollection -> [(Key, Direction)] -> Unique -> IO ByteStringSource
Create a new index on FullCollection on the list of Key / Direction pairs.
dropIndex :: Connection -> FullCollection -> [(Key, Direction)] -> IO ()Source
Drop the specified index on the given FullCollection.
dropIndexes :: Connection -> FullCollection -> IO ()Source
Drop all indexes on FullCollection.
indexInformation :: Connection -> FullCollection -> IO [BsonDoc]Source
Return a BsonDoc describing the existing indexes on FullCollection.
With the current server versions (1.2) this will return documents such as:
{"key": {"lastname": -1, "firstname": 1}, "name": "lastname_-1_firstname_1", "ns": "mydb.people", "unique": true}
Which is a single key that indexes on lastname
(descending) and
then firstname
(ascending) on the collection people
of the
database mydb
with a uniqueness requirement.
Map-Reduce
data MapReduceOpt Source
MROptQuery BsonDoc | query filter object |
MROptLimit Int64 | number of objects to return from collection |
MROptOut ByteString | output-collection name |
MROptKeepTemp | If set the generated collection is not treated as temporary, as it will be by defualt. When MROptOut is specified, the collection is automatically made permanent. |
MROptFinalize JSCode | function to apply to all the results when finished |
MROptScope BsonDoc | can pass in variables that can be access from mapreducefinalize |
MROptVerbose | provide statistics on job execution time |
:: Connection | |
-> FullCollection | |
-> JSCode | mapping javascript function |
-> JSCode | reducing javascript function |
-> [MapReduceOpt] | |
-> IO Cursor |
Run map/reduce and produce a cursor on the results.
:: Connection | |
-> FullCollection | |
-> JSCode | mapping javascript function |
-> BsonDoc | Scope for mapping function |
-> JSCode | reducing javascript function |
-> BsonDoc | Scope for mapping function |
-> [MapReduceOpt] | |
-> IO Cursor |
Run map/reduce with associated scopes and produce a cursor on the results.
:: Connection | |
-> FullCollection | |
-> JSCode | mapping javascript function |
-> JSCode | reducing javascript function |
-> [MapReduceOpt] | |
-> IO BsonDoc |
Issue a map/reduce command and return the results metadata. If
all you care about is the actual map/reduce results you might want
to use the mapReduce
command instead.
The results meta-document will look something like this:
{"result": "tmp.mr.mapreduce_1268095152_14", "timeMillis": 67, "counts": {"input": 4, "emit": 6, "output": 3}, "ok": 1.0}
The results field is the collection name within the same Database that contain the results of the map/reduce.
:: Connection | |
-> FullCollection | |
-> JSCode | mapping javascript function |
-> BsonDoc | Scope for mapping function |
-> JSCode | reducing javascript function |
-> BsonDoc | Scope for reducing function |
-> [MapReduceOpt] | |
-> IO BsonDoc |
Issue a map/reduce command with associated scopes and return the
results metadata. If all you care about is the actual map/reduce
results you might want to use the mapReduce
command instead.
See runMapReduce
for more information about the form of the
result metadata.
mapReduceResults :: Connection -> Database -> BsonDoc -> IO CursorSource