- Haskell Data Analysis Cookbook
- Nishant Shukla
- 236字
- 2021-12-08 12:43:33
Using MongoDB queries in Haskell
MongoDB is a nonrelational schemaless database. In this recipe, we will obtain all data from MongoDB into Haskell.
Getting ready
We need to install MongoDB on our local machine and have a database instance running in the background while we run the code in this recipe.
MongoDB installation instructions are located at http://www.mongodb.org. On Debian-based operating systems, we can use apt-get
to install MongoDB, using the following command line:
$ sudo apt-get install mongodb
Run the database daemon by specifying the database file path as follows:
$ mkdir ~/db $ mongod --dbpath ~/db
Fill up a "people"
collection with dummy data as follows:
$ mongo > db.people.insert( {first: "Joe", last: "Shmoe"} )
Install the MongoDB package from Cabal using the following command:
$ cabal install mongoDB
How to do it...
- Use the
OverloadedString
andExtendedDefaultRules
language extensions to make the MongoDB library easier to use:{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-} import Database.MongoDB
- Define and implement
main
to set up a connection to the locally hosted database. Run MongoDB queries defined in therun
function as follows:main :: IO () main = do let db = "test" pipe <- runIOE $ connect (host "127.0.0.1") e <- access pipe master db run close pipe print e
- In
run
, we can combine multiple operations. For this recipe,run
will only perform one task, that is, gather data from the"people"
collection:run = getData getData = rest =<< find (select [] "people") {sort=[]}
How it works...
A pipe is established by the driver between the running program and the database. This allows running MongoDB operations to bridge the program with the database. The find
function takes a query, which we construct by evoking the select :: Selector -> Collection -> aQueryOrSelection
function.
Other functions can be found in the documentation at http://hackage.haskell.org/package/mongoDB/docs/Database-MongoDB-Query.html.
See also
If the MongoDB database is on a remote server, refer to the Reading from a remote MongoDB server recipe to set up a connection with remote databases.
- Mastering phpMyAdmin 3.4 for Effective MySQL Management
- Android 7編程入門經典:使用Android Studio 2(第4版)
- Java Web程序設計
- 網絡爬蟲原理與實踐:基于C#語言
- Modern JavaScript Applications
- 飛槳PaddlePaddle深度學習實戰
- Oracle 18c 必須掌握的新特性:管理與實戰
- Android系統級深入開發
- Scala Reactive Programming
- Emgu CV Essentials
- Azure Serverless Computing Cookbook
- HTML5+CSS3+jQuery Mobile APP與移動網站設計從入門到精通
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- 測試架構師修煉之道:從測試工程師到測試架構師
- 從零開始學Python大數據與量化交易