TulipeMoutarde.be

About

Embedded Document with Voyage in MongoDB

Written on May 24 2012.

This blog post was written a long time ago and may not reflect my current opinion or might be technically out of date. Read with a grain of salt.

In my previous post. I was wondering how Voyage would handle embedded documents. The answer is pretty simple. Let’s see with an example ( MQ stands for for Mars Quest):

Object subclass: #MQSpaceship
   instanceVariableNames: 'pilot name'
   classVariableNames: ''
   poolDictionaries: ''
   category: 'MarsQuest'

Object subclass: #MQPilot
   instanceVariableNames: 'name'
   classVariableNames: ''
   poolDictionaries: ''
   category: 'MarsQuest'

MQSpaceship class>>isPersistent
   ^true

MQPilot class>>isPersistent
   ^true

Generate the accessors for the instance variables (yeah, name is super annoying). And execute the following:

(MQSpaceship new
    name: 'Batmobile';
    pilot: (MQPilot new name: 'Batman')) save.

Voyage will generate two collection in your database: spaceship and pilot. The spaceship record we’ve just created is:

{
   "_id": ObjectId("f65bd8790000000000000000"),
   "#instanceOf": "MQSpaceship",
   "name": "Batmobile",
   "pilot": {
      "#collection": "pilot",
      "#instanceOf": "MQPilot",
      "__id": ObjectId("85f61e070000000000000000")
   }
}

And the pilot record:

{
  "_id": ObjectId("85f61e070000000000000000"),
  "#instanceOf": "MQPilot",
  "name": "Batman"
}

So we didn’t completely embed the Pilot into the Spaceship document but have defined a relation. This is something you would or wouldn’t want depending of your data and what kind of query you need to perform on them (this talk explains modeling choices in MongoDB).

When you retrieve the Spaceship, the Pilot is also automatically fetched.

Once again, this post is pretty straightforward and more a loud thinking about Voyage than a real structured tutorial/article. Hopefully it will end up in something useful for someone.

If not, you can always enjoy the uber cool hair design in the videoclip of Voyage, voyage from Desireless: