Getting Started with MongoDB using Scala


MongoDB is a document oriented NoSQL database which has gained tremendous popularity on account of its performance and scalability characteristics. It positions itself in the sweet spot near RDBMS which provide depth of functionality and memcache for scalability and performance characteristics.

In this post, we would look at connecting with MongoDB running on the local system with a Scala client.

To install MongoDB, follow the steps mentioned here. Once you follow the steps, you would be able to execute MongoDB as

vikas@vikas-laptop:~/w/software/archive/mongodb-linux-i686-2.0.2/bin$ mongod
mongod --help for help and startup options
Sat Feb  4 23:19:33 
Sat Feb  4 23:19:33 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Sat Feb  4 23:19:33 

This would start the MongoDB server. To do a quick test, open another terminal and do the following

vikas@vikas-laptop:~/w/software/archive/mongodb-linux-i686-2.0.2/bin$ mongo
MongoDB shell version: 2.0.2
connecting to: test
> show dbs;
local	0.0625GB
test	0.0625GB
> 

So we can connect to the MongoDB with the client that we used.

Now, let us see how we can connect to MongoDB with a Scala client. The official driver for Scala is Casbah.

If you are using sbt 0.11x, then you would need to do the following to include the driver as a part of your build.scala

object ApplicationBuild extends Build {

    val appName         = "MyCoolApp"
    val appVersion      = "1.0"

    val appDependencies = Seq(
      "com.mongodb.casbah" %% "casbah" % "2.1.5-1",
      // Add your project dependencies here,
    )

    val main = PlayProject(appName, appVersion, appDependencies).settings(defaultScalaSettings:_*).settings(
      // Add your own project settings here      
    )
}

Once you have the dependency, let us write a small App to access the database.

import com.mongodb.casbah.Imports._

object MongoTest extends App {

  connectToMongo

  def connectToMongo {
    val mongoConn = MongoConnection()
    val mongoColl = mongoConn("test")("vikas")
    val bread1 = MongoDBObject("name" -> "parrys",
      "price" -> "10 INR")
    val bread2 = MongoDBObject("name" -> "breadAndMore")
    mongoColl += bread1
    mongoColl += bread2
    mongoColl.find()

    for { x <- mongoColl } yield println("value "+ x)
  }
}

This small program does the following

Connects to the database called “test” and the collection called “vikas” For those of us from the RDBMS world, a collection is equivalent to a table. For more NoSQL to RDBMS mapping, refer to this chart.

So we create a MongoCollection and then we add MongoDBObjects to the collection using mongoColl += bread1. This inserts documents into our collection. Then we issue a find on the collection and get the following results

23:34:41.072 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Registering Scala Conversions.
23:34:41.076 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Deserializers for Scala Conversions registering
23:34:41.077 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Serializers for Scala Conversions registering
23:34:41.078 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up OptionSerializer
23:34:41.114 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up ScalaJCollectionSerializer
23:34:41.158 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up ScalaRegexSerializers
23:34:41.159 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Hooking up scala.util.matching.Regex serializer
23:34:41.160 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Reached base registration method on MongoConversionHelper.
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Registering Scala Conversions.
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Deserializers for Scala Conversions registering
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Serializers for Scala Conversions registering
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up OptionSerializer
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up ScalaJCollectionSerializer
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Setting up ScalaRegexSerializers
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Hooking up scala.util.matching.Regex serializer
23:34:41.626 [main] DEBUG c.m.c.c.c.s.RegisterConversionHelpers$ - Reached base registration method on MongoConversionHelper.
value { "_id" : { "$oid" : "4f2d733944ae57332d00eb55"} , "name" : "parrys" , "price" : "10 INR"}
value { "_id" : { "$oid" : "4f2d733944ae57332d00eb56"} , "name" : "breadAndMore"}

If we went back to our terminal and issued the following command, we would be able to get the same results

vikas@vikas-laptop:~/w/software/archive/mongodb-linux-i686-2.0.2/bin$ mongo
MongoDB shell version: 2.0.2
connecting to: test
> use test
switched to db test
> db["vikas"].find()
{ "_id" : ObjectId("4f2d733944ae57332d00eb55"), "name" : "parrys", "price" : "10 INR" }
{ "_id" : ObjectId("4f2d733944ae57332d00eb56"), "name" : "breadAndMore" }
> 

Next, we will try to see how to easily use Salat for MongoDB access.

About Vikas Hazrati

Vikas is the Founding Partner @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. Knoldus does niche Reactive and Big Data product development on Scala, Spark and Functional Java. Knoldus has a strong focus on software craftsmanship which ensures high-quality software development. It partners with the best in the industry like Lightbend (Scala Ecosystem), Databricks (Spark Ecosystem), Confluent (Kafka) and Datastax (Cassandra). To know more, send a mail to hello@knoldus.com or visit www.knoldus.com
This entry was posted in Scala and tagged , , , . Bookmark the permalink.

4 Responses to Getting Started with MongoDB using Scala

  1. Pingback: 2012년 2월 6일 it 기술 동향 |

  2. Pingback: Using MongoDB in Scala with Salat | Knoldus

  3. Pingback: Using MongoDB in Scala with Salat | Knoldus | Programmer Solution

  4. Pingback: Getting Started with MongoDB using Scala | Database | Syngu

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s