Introduction

In this guide, we'll provide a primer on working with MongoDB and Ruby on Rails. MongoDB is a popular NoSQL database known for its flexibility, while Ruby on Rails is a powerful web application framework. You'll learn how to integrate MongoDB into a Rails application, perform CRUD (Create, Read, Update, Delete) operations, and use the Mongoid ODM (Object-Document Mapping) library. Sample code and examples will help you get started.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • Ruby and Ruby on Rails installed on your system. You can install Rails using
    gem install rails
    .
  • MongoDB installed and running locally or accessible through a connection string.
  • A code editor or integrated development environment (IDE) for writing Rails applications.
  • The Mongoid gem installed. You can add it to your Rails project's Gemfile.

Step 1: Setting Up Your Rails Application

Start by creating a new Rails application. In your terminal, run the following command:

rails new my-mongoid-app

This will create a new Rails application with a basic directory structure.


Step 2: Configuring Mongoid for MongoDB

To use MongoDB with Rails, configure Mongoid as your Object-Document Mapping (ODM) library. Open the

config/application.rb
file and add the following code:

# config/application.rb
module MyMongoidApp
class Application < Rails::Application
config.generators do |g|
g.orm :mongoid
end
end
end

Step 3: Creating a Model

Create a model that represents the data you want to store in MongoDB. For example, if you're building a blog application, you can create a Post model:

rails generate model Post title:string content:text

This generates a model file in the

app/models
directory.


Step 4: Performing CRUD Operations

You can now perform CRUD operations on your MongoDB database using Mongoid. Here are some basic examples:

Create (Insert) Data

post = Post.new(title: 'My First Post', content: 'This is the content of my post.')
post.save

Read (Query) Data

# Find all posts
posts = Post.all
# Find a post by ID
post = Post.find('your-post-id')

Update Data

post = Post.find('your-post-id')
post.update(title: 'Updated Title')

Delete Data

post = Post.find('your-post-id')
post.destroy

Conclusion

You've now been introduced to working with MongoDB and Ruby on Rails using the Mongoid library. This primer covers the basics of setting up your Rails application, configuring Mongoid, creating a model, and performing CRUD operations. With these foundational skills, you can explore more advanced MongoDB and Rails features and build web applications with confidence.