官术网_书友最值得收藏!

Reading from a remote MongoDB server

In many cases, it may be more feasible to set up a MongoDB instance on a remote machine. This recipe will cover how to obtain data from a MongoDB hosted remotely.

Getting ready

We should create a remote database. MongoLab (https://mongolab.com) and MongoHQ (http://www.mongohq.com) offer MongoDB as a service and have free options to set up a small development database.

Tip

These services will require us to accept their terms and conditions. For some of us, it may be best to host the database in our own remote server.

Install the MongoDB package from Cabal as follows:

$ cabal install mongoDB

Also, install the helper following helper libraries as follows:

$ cabal install split
$ cabal install uri

How to do it...

  1. Use the OverloadedString and ExtendedDefaultRules language extensions required by the library. Import helper functions as follows:
    {-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}
    import Database.MongoDB
    import Text.URI
    import Data.Maybe
    import qualified Data.Text as T
    import Data.List.Split
  2. Specify the remote URI for the database connection as follows:
    mongoURI = "mongodb://user:pass@ds12345.mongolab.com:53788/mydb"
  3. The username, password, hostname, port address number, and database name must be extracted from the URI, as presented in the following code snippet:
    uri = fromJust $ parseURI mongoURI
    
    getUser = head $ splitOn ":" $ fromJust $ uriUserInfo uri
    
    getPass = last $ splitOn ":" $ fromJust $ uriUserInfo uri
    
    getHost = fromJust $ uriRegName uri
    
    getPort = case uriPort uri of 
        Just port -> show port 
        Nothing -> (last.words.show) defaultPort
    
    getDb = T.pack $ tail $ uriPath uri
  4. Create a database connection by reading the host port of the remote URI as follows:
    main :: IO ()
    main = do
        let hostport = getHost ++ ":" ++ getPort
        pipe <- runIOE $ connect (readHostPort hostport)
        e <- access pipe master getDb run
        close pipe
        print e
  5. Optionally authenticate to the database and obtain data from the "people" collection as follows:
    run = do
      auth (T.pack getUser) (T.pack getPass)
      getData
    
    getData = rest =<< find (select [] "people") {sort=[]}

See also

If the database is on a local machine, refer to the Using MongoDB queries in Haskell recipe.

主站蜘蛛池模板: 江西省| 福海县| 库尔勒市| 湘西| 桐城市| 永州市| 青海省| 襄城县| 通辽市| 铜鼓县| 宜宾县| 阿瓦提县| 三都| 遂川县| 堆龙德庆县| 万年县| 唐河县| 白银市| 大埔县| 吉木萨尔县| 大宁县| 吉木乃县| 道孚县| 云浮市| 新兴县| 辉南县| 满洲里市| 吴川市| 舒城县| 富裕县| 平遥县| 道孚县| 花莲县| 会东县| 托克逊县| 阳山县| 海门市| 昭通市| 包头市| 武穴市| 贵德县|