Quick Start: Scala + MongoDB

2010-07-19

After completing the following steps you have a sbt project with some running sample code that demonstrates the usage of mongoDB from Scala.

I assume you have installed java 1.5+ and a working installation of sbt. Some instructions on installing sbt can be found here .

Create your project

Open a new terminal and type the following commands.

mkdir mongo_howto
cd mongo_howto
sbt

Answer some questions asked by sbt:

Project does not exist, create new project? (y/N/s) y
Name: mongo_howto
Organization: mrico
Version [1.0]:
Scala version [2.7.7]: 2.8.0
sbt version [0.7.4]:
:: retrieving :: org.scala-tools.sbt#boot-scala
confs: [default]
2 artifacts copied, 0 already retrieved (9911kB/797ms)
Getting org.scala-tools.sbt sbt_2.7.7 0.7.4 ...
...
[info] Building project smongo 1.0 against Scala 2.8.0
[info]    using sbt.DefaultProject with sbt 0.7.4 and Scala 2.7.7

sbt is running and awaits your commands. For now we quit sbt by typing exit.

> exit
[info]
[info] Total session time: 889 s, completed
[success] Build completed successfully.

Add mongo-scala-driver as a dependency

To connect to a mongo server we need a driver that knows how to communicate with the server.

We use the mongo-scala-driver which is a thin wrapper around mongo-java-driver. The source code can be found on github. Instead of manually downloading the libray we let sbt manage our dependencies.

To do so we do the following steps …

Create a new folder called project/build:

mkdir project/build

Create the sbt project configuration file:

vi project/build/Project.scala
import sbt._

class MongoProject(info: ProjectInfo) extends DefaultProject(info) {
val mongo = "com.osinka" % "mongo-scala-driver_2.8.0" % "0.8.2"
}
:xw

Launch sbt and update your project dependencies:

sbt
[info] Recompiling project definition...
[info]    Source analysis: 1 new/modified, 0 indirectly invalidated, 0 removed.
[info] Building project smongo 1.0 against Scala 2.8.0
[info]    using MyProject with sbt 0.7.4 and Scala 2.7.7
> update
[info]
[info]  update </notextile>
[info] :: retrieving :: mrico#smongo_2.8.0 [sync]
[info]  confs: [compile, runtime, test, provided, system, optional, sources, javadoc]
[info]  0 artifacts copied, 2 already retrieved (0kB/63ms)
[info]  update </notextile>
[success] Successful.
[info]
[info] Total time: 2 s, completed
> exit

Now you should have two jars below the lib_managed folder of your project.

Install and run mongodb

Before we start coding, I think it is a great idea to have mongodb installed. If you already have a running mongodb installation you can certainly skip this step.

Open your browser and browse to http://www.mongodb.org/downloads.

Choose and download the distribution and unpack it.

tar zxf mongodb-osx-x86_64-1.4.4.tgz

Open a new terminal and start the mongo server:

cd {path_to}/mongodb-osx-x86_64-1.4.4
mkdir data
bin/mongod --dbpath data

Now you should see something like:

waiting for connections on port 27017
web admin interface listening on port 28017

That‘s it. Your mongodb server is up and running!

Hacking some client code

Launch sbt again and type console to execute the Scala REPL.

sbt
> console
Welcome to Scala version 2.8.0.final (Java HotSpot(TM) Client VM, Java 1.7.0-ea)
.
Type in expressions to have them evaluated.
Type :help for more information.
scala>

Copy/Paste the following demo code to see it working:

import com.osinka.mongodb._
import com.osinka.mongodb.shape._
import com.mongodb._

// data structure
case class Address(
name: String,
street: String,
zipCode: String,
city: String
) extends MongoObject

// factory
object Address extends MongoObjectShape[Address] {
lazy val name = Field.scalar("name", _.name)
lazy val street = Field.scalar("street", _.street)
lazy val zipCode = Field.scalar("zipCode", _.zipCode)
lazy val city = Field.scalar("city", _.city)

override lazy val * = List(name, street, zipCode, city)
override def factory(dbo: DBObject): Option[Address] =
for {
name(n) <- Some(dbo)
street(s) <- Some(dbo)
zipCode(z) <- Some(dbo)
city(c) <- Some(dbo)
} yield new Address(n, s, z, c)
}

// connect to mongo server
val m = new Mongo("localhost")
val db = m.getDB("test")
val coll = db.getCollection("addresses") of Address

// insert
coll << new Address("Joe Developer", "Street", "B384DJ3", "Somewhere")

// query
for { a <- Address where { Address.street is "Street" } in coll } println(a)

That‘s it.


me

Marco Rico Gomez is a passionate software developer located in Germany who likes to share his thoughts and experiences about software development and technologies with others.


blog comments powered by Disqus