CopyPastehas never been so tasty!

MongoDB basics and usage with Ruby on Rails

by anonymous

  • 0
  • 0
  • 0
84 views

In our last article we discussed  why you would want to use NoSQL database in your project. So, let’s pick up from there and cover the basics of MongoDB 

MongoDB is a collection-oriented, schema-free and document based database. It is scalable, high-

performance, open source and written in C++. Key feature from a developer’s perspective would

be its powerful query language.

 

The official sitehas pretty good documentation, so we will just summarize the key concepts here.

 

Terminology:

Document – is a group of key-value pairs (similar to a hash in ruby), where keys are strings and

values are any of a rich set of supported data types. You can think of it as a row in a relational

database, with keys being the column names. Document data is stored in BSON (“Binary Serialized

dOcument Notation”) format. Example:

 

status = { posted_at : Date("2012-06-19T02:10:11.3Z"),

  author : "Mohammad",

  title : "Learning MongoDB basics",

  text : "This can be a very long description...",

  tags : [ "MongoDB", "Rails" ],

  likes : 20 }

 

BSON – is a binary-encoded serialization of JSON-like documents. BSON is designed to be

lightweight, traversable, and efficient. BSON, like JSON, supports embedding of objects and arrays

within other objects and arrays. 

 

Data Types – Mongo supports all basic JSON data types like string, integer, boolean, double, null,

array, and object, as well as special data types like date, object_id, binary data, regular expression,

and code.

 

Collection – is a group of documents, usually having a similar structure. You can think of it as a

table in a relational database.

 

Indexing – is similar to how it works in relational databases. Every document gets a default index

on the “_id” attribute, which also acts as a primary key.

 

Embedding – is the nesting of objects and arrays inside a document like pre-joined data or like a

‘view’ in relational database. So, for example all the comments on a photo can be embedded

within the photo document itself instead of storing them in a different collection. Example:

 

status = { posted_at : Date("2012-06-19T02:10:11.3Z"),

  author : "Mohammad",

  title : "Learning MongoDB basics",

  text : "This can be a very long description...",

  tags : [ "MongoDB", "Rails" ],

  likes : 20,

  comments: [


 

    {from  “Chirag”,

      commented_at: Date("2012-06-19T02:50:11.3Z"),

      comment  “Yes, it is pretty cool!”}

  ]}

 

Links – are references between documents, like foreign keys.

 

Joins – are not supported in MongoDB. However, some data can be de-normalized and embedded

within the parent document (like in the photo example above) to remove the need for joins.

 

Restrictions – Document element name cannot begin with “$” or contain a “”  “_id” is reserved

element name (primary key) and cannot be reused for any other purpose.

 

Syntax:

It would be good to try this out in a mongo console as we go.

Console

~$ mongo 

> help                                         // top level help

> db.help()                                // help on db-specific methods

> db.mycollection.help()        // help on collection methods

 

Query

db.createCollection("users")                         // Create a new collection

db.users.find()                                                  // Find all documents from a collection

db.users.find({}, {name:1,email:1})              // Get name and email of all users

db.users.find({age:33}, {name:1,email:1})  // Get name and email of all users older than 33 years 

db.users.findOne({name: 'mohammad'})   // Find first document with a given name

 

Insert

db.users.insert({name: 'chirag')

doc = {name: 'mohammad', email : 'mohammad@rails.com'}

db.users.save(doc)

 

Update

db.users.update({name:'mohammad'}, {$set:{name:'Mohammad'}})

 

Delete & Drop

db.users.remove({name:'mohammad'})

db.users.drop() 

 

Indexing

db.users.ensureIndex({name: 1})

db.users.dropIndex({name : 1})

db.users.findIndexes()

 

For better understanding, you can go through SQL to Mongo reference here.

 

ORM for Rails:

There are several ActiveRecord replacements for MongoDB, but we have foundMongoMapperto


 

 

 

 

be the closest replacement. There is already a greatRailscaston how to use MongoMapper with

 

Rails, so we won’t cover that in this article.

 

 

 

 

 

Get more information on: Ruby on Rails For more information visit: Web Application Developer

In our last article we discussed why you would want to use NoSQL database in your project. So,

let’s pick up from there and cover the basics of MongoDB 

 

MongoDB is a collection-oriented, schema-free and document based database. It is scalable, high-

performance, open source and written in C++. Key feature from a developer’s perspective would

be its powerful query language.

 

The official sitehas pretty good documentation, so we will just summarize the key concepts here.

 

Terminology:

Document – is a group of key-value pairs (similar to a hash in ruby), where keys are strings and

values are any of a rich set of supported data types. You can think of it as a row in a relational

database, with keys being the column names. Document data is stored in BSON (“Binary Serialized

dOcument Notation”) format. Example:

 

status = { posted_at : Date("2012-06-19T02:10:11.3Z"),

  author : "Mohammad",

  title : "Learning MongoDB basics",

  text : "This can be a very long description...",

  tags : [ "MongoDB", "Rails" ],

  likes : 20 }

 

BSON – is a binary-encoded serialization of JSON-like documents. BSON is designed to be

lightweight, traversable, and efficient. BSON, like JSON, supports embedding of objects and arrays

within other objects and arrays. 

 

Data Types – Mongo supports all basic JSON data types like string, integer, boolean, double, null,

array, and object, as well as special data types like date, object_id, binary data, regular expression,

and code.

 

Collection – is a group of documents, usually having a similar structure. You can think of it as a

table in a relational database.

 

Indexing – is similar to how it works in relational databases. Every document gets a default index

on the “_id” attribute, which also acts as a primary key.

 

Embedding – is the nesting of objects and arrays inside a document like pre-joined data or like a

‘view’ in relational database. So, for example all the comments on a photo can be embedded

within the photo document itself instead of storing them in a different collection. Example:

 

status = { posted_at : Date("2012-06-19T02:10:11.3Z"),

  author : "Mohammad",

  title : "Learning MongoDB basics",

  text : "This can be a very long description...",

  tags : [ "MongoDB", "Rails" ],

  likes : 20,

  comments: [


 

    {from  “Chirag”,

      commented_at: Date("2012-06-19T02:50:11.3Z"),

      comment  “Yes, it is pretty cool!”}

  ]}

 

Links – are references between documents, like foreign keys.

 

Joins – are not supported in MongoDB. However, some data can be de-normalized and embedded

within the parent document (like in the photo example above) to remove the need for joins.

 

Restrictions – Document element name cannot begin with “$” or contain a “”  “_id” is reserved

element name (primary key) and cannot be reused for any other purpose.

 

Syntax:

It would be good to try this out in a mongo console as we go.

Console

~$ mongo 

> help                                         // top level help

> db.help()                                // help on db-specific methods

> db.mycollection.help()        // help on collection methods

 

Query

db.createCollection("users")                         // Create a new collection

db.users.find()                                                  // Find all documents from a collection

db.users.find({}, {name:1,email:1})              // Get name and email of all users

db.users.find({age:33}, {name:1,email:1})  // Get name and email of all users older than 33 years 

db.users.findOne({name: 'mohammad'})   // Find first document with a given name

 

Insert

db.users.insert({name: 'chirag')

doc = {name: 'mohammad', email : 'mohammad@rails.com'}

db.users.save(doc)

 

Update

db.users.update({name:'mohammad'}, {$set:{name:'Mohammad'}})

 

Delete & Drop

db.users.remove({name:'mohammad'})

db.users.drop() 

 

Indexing

db.users.ensureIndex({name: 1})

db.users.dropIndex({name : 1})

db.users.findIndexes()

 

For better understanding, you can go through SQL to Mongo reference here.

 

ORM for Rails:

There are several ActiveRecord replacements for MongoDB, but we have foundMongoMapperto


 

 

be the closest replacement. There is already a greatRailscaston how to use MongoMapper with

Rails, so we won’t cover that in this article.

Add A Comment: