16.3. Connecting to MongoDB and Inserting Data
Problem
You want to use the MongoDB database with a Scala application, and want to learn how to connect to it, and insert and retrieve data.
Solution
If you don’t already have a MongoDB installation, download and install the MongoDB software per the instructions on its website. (It’s simple to install.) Once it’s running, use the Casbah driver with your Scala application to interact with MongoDB.
In development, I start my test instance of MongoDB from its installation directory with this command:
$ bin/mongod -vvvv --dbpath /Users/Al/data/mongodatabases
This starts the MongoDB server in a verbose mode, using the
directory shown for its databases. After a lot of output, the last few
lines from the mongod
command look
like this:
Sun Sep 16 14:27:34 [websvr] admin web console waiting for connections on port 28017 Sun Sep 16 14:27:34 [initandlisten] waiting for connections on port 27017
To demonstrate Casbah, build a small application. First, create a simple SBT project directory structure, as demonstrated in Recipe 18.1.”
Note
You can follow along by cloning my GitHub project.
Second, create your build.sbt file, specifically including the Casbah driver dependency:
name := "MongoDBDemo1" version := "1.0" scalaVersion := "2.10.0" libraryDependencies ++= Seq( "org.mongodb" %% "casbah" % "2.6.0", "org.slf4j" % "slf4j-simple" % "1.6.4" ) scalacOptions += "-deprecation"
The SLF4J library shown isn’t necessary for a simple example, but including it gets ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.