MongoDB Ruby Driver

优质
小牛编辑
139浏览
2023-12-01

Getting started

Once the MongoDB Ruby driver is installed, we can begin to use it to connect to a Mongo database. To create a connection using localhost, we simply specify the driver as a dependency. Assuming we’re using the default port we can then connect as follows:

require 'mongo'

# where 'learning-mongo' is the name of our database:
db = Connection.new.db('learning-mongo');

We probably also want to place some data into learning-mongo. It could be as simple as a note, so why don’t we go ahead and begin a notes collection?:

ruby notes = db.collection('notes') Something interesting worth noting is that at this point, we haven’t actually created the database nor the collection we’re referencing above.

Neither of these items exist in Mongo (just yet) but as we’re working with a new database but they will once we insert some real data.

A new note could be defined using key/value pairs as follows and then inserted into learning-mongo using collection.insert():

our_note = { :text => 'Remember the milk', :remindInterval => 'weekly'}
note_id = notes.insert(our_note)

What is returned from inserting a note into the notes collection is an ObjectId reference for the note from Mongo. This is useful as we can re-use it to locate the same document in our database.

note = notes.find( :id => note_id ).first

This can also be used in conjunction with Mongo’s collection.update() method and query operators (i.e $set) to replace fields in an existing document.

We might update an entire document as follows:

note = notes.find( :id => note_id ).first
note[:text] = 'Remember the bread'
notes.update({ :_id => note_id }, note)

or using $set, update an existing document without overwriting the entire object as like this:

notes.update({ :_id => note_id }, '$set' => { :text = > 'Remember the bread' })

Useful to know: Almost each MongoDB document has an _id field as its first attribute. This can normally be of any type, however a special BSON datatype is provided for object ids. It’s a 12-byte binary value that has a high probability of being unique when allocated.

Note: Whilst we opted for the MongoDB Ruby Driver for this stack, you may also be interested in DataMapper - a solution which allows us to use the same API to talk to a number of different datastores. This works well for both relational and non-relational databases and more information is available on the official project page. Sinatra: The Book also contains a brief tutorial on DataMapper for anyone interested in exploring it further.