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

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.

主站蜘蛛池模板: 灵璧县| 芜湖县| 中方县| 新泰市| 和顺县| 武川县| 桐城市| 盘锦市| 赣榆县| 大城县| 得荣县| 义马市| 加查县| 长丰县| 西峡县| 安顺市| 阜南县| 仙桃市| 鄂州市| 萨迦县| 台中县| 金川县| 大悟县| 蒙自县| 会同县| 定南县| 康平县| 杭锦旗| 开远市| 平谷区| 抚州市| 赫章县| 宁陕县| 乌兰察布市| 迁安市| 枣强县| 道孚县| 珲春市| 贺州市| 东平县| 黄山市|