Monday, January 3, 2011

First post, but not useless - Moongo my Java library for NoSQL MongoDB

Hi to all,
I just want to share with all of you, interested, my first post.
My first post is concerning another "my first time"... github!
@ this link you will find my open source project about MongoDB, Moongo!

Creativity and fantasy are not my best (artistically speaking - lol), so what it is all about?

Moongo is a Java library, which aims to be an easy interface to play with MongoDB.
There are two main objects you would use with Moongo:

  1. Moongo
  2. QueryObject

The first one, is the main object which wraps all methods you have/need to use.
The second one, is the object used to create query criteria.

With Moongo you just have to write the code for your pojos and give them to Moongo.
Here is an example:

User user = new User();
Moongo moongo = new Moongo();

Now you can check into your MongoDB instace for your fresh new document:

>use test;
switched to test
>show collections;
{ "_id" : ObjectId("4d1b3fc97b060183d154b8fd"), "firstName" : "Luigi", "lastName" : "Foogaro"}

Moongo it supports embedded documents as well, here is another example:

Location location = new Location();
Nation nation = new Nation();
City city = new City();

Now if you look into your MongoDB instance you will find:

{ "_id" : ObjectId("4d1b3fc97b060183d154c099"), "nation" : { "code" : "IT", "name" : "Italy", "city" : { "code" : "RM", "name" : "Rome" } } }

When creating new documents, only the root document gets an ObjectId, unless... keep reading :)

Thinking about redundancy?
Moongo supports DBRef, just annotate your embedded documents with @DBReferenced and you are done!
From the previous example:

public class Location {
    @DBReferenced Nation nation;

Looking back again into your MongoDB instance you should have two more collections with their first new document:

>show collections;
{ "_id" : ObjectId("4d1b3fc97b060183d154c100"), "nation" : { "$ref" : "com.foogaro.nosql.moongo.Nation", "$id" : "4d1b3fc97b060183d154c101" } } >;
{ "_id" : ObjectId("4d1b3fc97b060183d154c101"), "code" : "IT", "name" : "Italy", "city" : { "code" : "RM", "name" : "Rome" } }

Obviously if you would have annotated City inside Nation, you would have got the Nation collection document without the City embedded document, just its reference, and the City collection with its document as well.

Moongo will take care of all mapping to/from database. So retrieving the Location document with id "4d1b3fc97b060183d154c100" from MongoDB, you will get back a Location pojo as well as with its Nation property populated with its City property populated.

Location location = new Location();
location.set_id(new ObjectId("4d1b3fc97b060183d154c100"));
Location persistedLocation = (Location);

You might want to wrap the call to your Moongo to avoid casting everytime.

That's all for now,
stay tuned for upcoming releases and tips.


1 comment: