An Evening with MongoDB

An Evening with MongoDB

Few months back, I was planning for my major project at college. I was pretty confused since I didn’t wanted to work with PHP and MySQL that was the time when Abhishek suggested about MongoDB. Initially I faced a little bit difficulty due to the transition from schema to schema-less database. The best part that kept to hooked to it was the simplicity since it allows to keep the focus on the application and the database automatically adapts to the changes. Now after working on MongoDB for quite a long time and tackling various issues I thought of writing this article. It is divided into four phases consisting of Installation and Configuration, Working with MongoDB Shell, Working with PHP and MongoDB, and finally Working with node.js and MongoDB. This article is dedicated to the Facebook Group of MongoDB Developers, check link at the end of the article.

Phase 1: Installation & Configuration

Installation is pretty simple but still I’ve added it for the fulfillment of this article.

For Windows Users: The following URL will guide you to install MongoDB and configure it for working with PHP.

[box type=”info”]www.pronique.com/blog/installing-mongodb-on-windows-the-wamp-way[/box]

For Linux Users: The following URL guides to install MongoDB based on the flavor used.

docs.mongodb.org/manual/tutorial/install-mongodb-on-linux/

The following is a set of commands to add the PHP driver for MongoDB on a Linux box.

sudo yum install php-pear| sudo apt-get install php-pear
sudo yum install php-devel | sudo apt-get install php-devel
sudo pecl install mongo
sudo echo 'extension=mongo.so' >> /etc/php.ini

Phase 2: Working with MongoDB Shell

Working with MongoDB shell is seriously fun. Following are some of the basic commands to start with:

> show dbs //Displays the list of database
> use //Selects a database
> show collections //Displays collections inside a database
> db..find() //Displays all the records inside a collection

The following code snippet helps in adding a user with password and set of roles to a database for authentication purposes.

> use
> db.addUser( { user: "", pwd: "", roles: [ "readWrite" ] } )

For correctly assigning roles to a user, the following link is quite helpful.

[box type=”info”]docs.mongodb.org/manual/reference/user-privileges/[/box]

We can also pass scripts written in simple javascript for interacting with the MongoDB shell. Following is a piece of code for adding a user “sadmin” with password “blog” with default privileges.

//Source Code of Mongo_addUser.js
db = db.getSiblingDB("shubhamoy"); // Selects or Creates the Database
db.addUser("sadmin", "blog");

Phase 3: Working with PHP and MongoDB

The following PHP function would return all the entries of the “emps” collection in the descending order.

public function getAllEmployees()
{
$m = new MongoClient("mongodb://scott:tiger@localhost:27017/employee"); //MongoDB Connection with Authentication on default port
$database = $m->selectDB( "employee" ); //MongoDB Database Selection
$db = $database->emps; //MongoDB Collection
$result=$db->find(array(), array("empno" => 1,"name" => 1, "deptno" => 1, "manager" => 1))->sort(array("_id" => -1)); //Query
return $result;
}

The main issue faced by developers coming from SQL background is with writing queries. QueryMongo.com allows to generate MongoDB queries from traditional MySQL queries. It is quite useful for understanding the basics though I won’t suggest it for advanced or real-world applications instead refer the MongoDB Documentation for writing advanced queries.

MongoDB can be easily integrated into CodeIgniter. Check out this repository for smooth integration  of MongoDB with CodeIgniter github.com/alexbilbie/MongoQB

Phase 4: Working node.js and MongoDB

Recently I was working on writing a HTTP Proxy server with node.js. It gave me an opportunity to integrate it with MongoDB. So we only need the MongoJS library for integrating MongoDB with node.js.  Following command will install the MongoJS module for node.js

[box type=”info”]npm install mongojs[/box]

Following are some snippets to start your work:

var m = require('mongojs'); //Include MongoJS Module
var db = m('myDB'); //Selects myDB Database
var contact = db.collection('contact'); //Selects contact Collection
contact.insert({name: name, age:age}, function(err, doc)
{
console.log("Record Inserted Successfully");
});

For more examples and sample code snippets. Check out: github.com/mafintosh/mongojs#usage

Acknowledgement

1. Abhishek Gahlot: The guy who introduced MongoDB and whose article(link) was quite useful in writing this article.

2. MongoDB Group on Facebook facebook.com/groups/mongodbgroup/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.