Boldr by N. Merouze

Getting started with Duby and MongoDB

I first talked about Duby back in November. The project has since evolved, there’s now more features and it’s more usable. I’m able to run MongoDB so I decided to share it. If you know nothing about Duby, read the README.

NOTE: The following example is based on the java example from the mongo-java-driver repo.

Setup

We first need to download the MongoDB jar and add its path to CLASSPATH:

$ export CLASSPATH=.:/my/path/to/mongo-1.2.jar

Then we create our Duby file we name MongoTest.duby.

Connection to MongoDB

We start by importing all we need:

Then get the DB connection:

Cool new feature: Iterators

One reason I love Ruby is because iterators are nice! This feature landed in Duby a while ago and it’s just a pleasure to use it (here to display collection names):

Inserting a new document

To insert a new document, we must get a collection:

To build a new document we need to use BasicDBObject as a container and there’s a BasicDBObject#put(key, value) to add information:

Of course we can put a BasicDBObject inside another BasicDBObject. And here’s how to insert the document we’ve just build:

Getting an existing document

Nothing really to say about how to get the document we’ve just inserted:

Executing the file

I hasn’t been able to run the file via duby MongoTest.duby I had to compile it then call it with Java dubyc -java MongoTest.duby && javac MongoTest.java && java MongoTest

Thoughts about Duby

  • dubyc -java converts Duby code to Java code. So you don’t have to worry about performance.
  • Duby code really feels like Ruby. And this feeling’s getting more and more true.
  • You can create a Duby class and use it in your Java code (unlike JRuby). It’s because “Duby is Java with Ruby syntax”. And it’s wonderful.
  • The true awesomeness is that you can create Android applications with Duby! Check out this example.

Are you excited now? You should be and try Duby right now!