Tuesday, July 2, 2013

Basic Ruby API

The official MongoDB Ruby API isn't for beginners so here are some notes.

Mongo::MongoClient

As with most databases, you connect to it via a client.  You create a new client whose constructor takes the connection parameters.

I haven't spotted any security parameters thus far (user/passwords, etc.)

A client allows one to access databases via the '[ ]' operation.  Accessing a database will create it if it doesn't exist.

Mongo::DB

A Mongo::DB holds multiple collections which are accessed via the '[ ]'  operation.  Accessing a collection will create it if it doesn't exist.

Mongo::Collection

For basic use, I've come think of a MongoDB collection as an unordered set of associative arrays (aka hash table). I use the word set to imply that there is no natural index to the collection.

One inserts a hashtable into a collection using the #insert method.  MongoDB will extend the associative array with an additional key/value.  The key is "_id" and the value is a BSON::ObjectId.


In his book "Domain-Driven Design", Eric Evans talks about object retrieval.  There are two basic patterns which are by-name and by-property.  In the basic mode of operation, we let MongoDB assign a name (the _id attribute) and we use properties to locate and retrieve objects.

No comments:

Post a Comment