Rate this article
Before discovering Ruby and Ruby on Rails, I was a .NET developer. At that time, I'd make ad-hoc changes to my development database, export my table/function/stored procedure/view definitions to text files, and check them into source control with any code changes. Using
difffunctionality, I'd compare the schema changes that the DBAs needed to apply to production and we'd script that out separately.
I'm sure better tools existed (and I eventually started using some of ), but I was looking for a change. At that time, the real magic of Ruby on Rails for me was the which made working with my database fit with my programming workflow. Schema management became less of a chore and there were
raketasks for anything I needed (applying migrations, rolling back changes, seeding a test database).
Schema versioning and management with Rails was leaps and bounds better than what I was used to, and I didn't think this could get any better — but then I found MongoDB.
When working with MongoDB, there's no need to
CREATE TABLE foo (id integer, bar varchar(255), ...); if a collection (or associated database) doesn't exist, inserting a new document will automatically create it for you. This means Active Record migrations are no longer needed as this level of schema change management was no longer necessary.
Having the flexibility to define my data model directly within the code without needing to resort to the intermediary management that Active Record had facilitated just sort of made sense to me. I could now persist object state to my database directly, embed related model details, and easily form queries around these structures to quickly retrieve my data.
When the document above is inserted, an
BSON::ObjectId('62d83d9dceb023b20aff228a')is created. All documents must have an . However, if not provided, a default
_idof type will be generated. When running the above, you will get a different value for
_id, or you may choose to explicitly set it to any value you like!
Our sample above demonstrated how to quickly create and read a document. Updating and deleting documents are just as painless as shown below:
The following example adapts the previous example to use Mongoid: