Getting Started with Spring Data – MongoDB in Scala

I used MongoDB for a project in 2010 and I had great experience with it. Unfortunately I didn’t get the chance to work with this agile and scalable document-oriented database again until now. But my current assignment has brought the opportunity to use it in production :)

In this post I want to show you a step by step guide on how you can start your Scala project with Spring Data for MongoDB.

You should have SBT 0.11 installed on your system since I am going to use it as the building tool through out this post.

1. Creating Project

Create the project like below:

Open file build.sbt and add the dependencies:

Save the file and run the following in SBT console:

And generate the IDE related files. I am using IntelliJ:

or if you use Eclipse:

Now you have configured your project and you can start coding!

2. Configuring Spring

There are two ways to configure Spring Data for MongoDB: Annotations and XML. I explain annotations here. You have to extend AbstractMongoConfiguration class as follows to define your database settings:

As you see there are two methods to implement. mongo method should return an instance of Mongo class. If you are using a mongo instance in a network, you should then specify the address and possibly port (if not the default).

3. Data Model

Consider we have the following class for keeping accounts in a system. This class will be mapped to a mongo document by Spring:

4. Interacting with MongoDB

Now let’s write a simple program to interact with MongoDB:

mongoTemplate is an implementation of MongoOperation interface. With MongoOperation you can do all CRUD operations. E.g. inserting/saving a document:

“accounts” is the name of collection. Or if you want to query:

Note that JavaConversions is required here since the result of find is a java.util.List[Account] and we need to convert it to Scala list.

Please refer to documentation of Spring Data for MongoDB for more info about what you can do more :)

This Post Has One Comment

  1. Great post. Thanks.

    How would you handle Option wrappers in your case class? This is needed for optional segments in your data model.

Leave a Reply

Close Menu