In this chapter you’ll build a Scala driver for MongoDB. MongoDB is a scalable, document-oriented database. You’ll build this driver incrementally using the object-oriented constructs provided by Scala, and along the way I’ll explain each concept in detail. Scala has made some object-oriented innovations, and one of them is the trait. Traits are similar to abstract classes with partial implementation. You’ll explore how to use traits when building Scala applications. As you move through the chapter, you’ll learn about Scala case classes. Case classes are useful when it comes to building immutable classes, particularly in the context of concurrency and data transfer objects. Case classes also allow Scala to bridge the gap between functional programming and OOP in terms of pattern matching. Without wasting any more time, let’s learn OOP programming in Scala by building a MongoDB driver.
Building a Scala MongoDB driver: user stories
To explore Scala’s object-oriented constructs and use, let’s build a MongoDB driver. While building this example driver, you’ll dive deep into concepts for a thorough understanding. You won’t need to start from scratch because you’ll use an existing Java driver for MongoDB. You’ll build a Scala wrapper over the Java MongoDB driver. That way, you don’t have to deal with the low-level MongoDB API and can focus on your objective of learning Scala.
The user stories you’ll be implementing in your Scala wrapper driver are as follows:
WHAT’S A USER STORY?
The format of the document in which the information is stored in MongoDB is BSON (binary JSON). Other document-based databases like Lotus Notes (IBM) and SimpleDB (Amazon.com) use XML for information storage. JSON has an added advantage when working with web-based applications because JSON content can be easily consumed with little transformation. A great place to get a feel for MongoDB is http://try.mongodb.org. Go ahead and download MongoDB (www.mongodb.org/display/DOCS/Downloads). Then, unpack it and run the following command to start the MongoDB server:
To connect to the MongoDB server, use the client shell that ships with the distribution of MongoDB:
At this point you should be ready to start building the Scala wrapper driver. If you’re interested in learning more about MongoDB, look at the MongoDB tutorial (www.mongodb.org/display/DOCS/Tutorial).