boldr by Nicolas Mérouze

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:

import com.mongodb.Mongo
import com.mongodb.DBCollection
import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.mongodb.DBCursor
import com.mongodb.DB

import java.util.Set
import java.util.List

Then get the DB connection:

begin
  m = Mongo.new
  db = m.getDB "mydb"
  # the rest of the code will go here
rescue Exception
end

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):

colls = db.getCollectionNames

colls.each do |coll|
  puts coll
end

Inserting a new document

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

testColl = db.getCollection "testCollection"
testColl.drop # drop the data from previous test

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

doc = BasicDBObject.new
doc.put "name", "MongoDB"
doc.put "type", "database"
doc.put "count", 1

info = BasicDBObject.new
info.put "x", 203
info.put "y", 102

doc.put "info", info

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

testColl.insert(doc)

Getting an existing document

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

myDoc = testColl.findOne
puts myDoc

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

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

If you liked the article and/or want to talk to me about it, you can follow me on twitter.