Implement joins in mongodb

How to implement joins in mongo db?

Joins in mongo db are implemented using map reduce terminology.

Lets consider a scenario where you have a collection of users and these users do have roles assigned to them. Now consider we have to apply join to determine role of user.

  • First we need to connect to mongo

> mongo

  • We need to select database to interact. This command will select faculties database if it already exists or create new if it doesn’t exists

> use faculties

  • Now we need to create collections over this db (which are like tables in mysql). Let’s create two collections one is users and other one is roles.

> db.createCollection(‘users’)

> db.createCollection(‘roles’)

  • Now next step is to add some record sets to these collections

> db.users.insert({name: ‘Jakxfzxgxes’, role:1})

> db.users.insert({name: ‘Jakxdghdfhfhes’, role:2})

> db.roles.insert({role_id:1, rolename:’HOD’})

> db.roles.insert({role_id:2, rolename:’Director’})

  • Now lets start process of applying join. For this first we need to create map function.

> var map = function()


var output = {name:,rolename:db.roles.findOne({role_id:this.role}).rolename};

emit(this._id, output);


  • Now time to create reduce function

> var reduce = function(key, values) {

var outs = {name:null, rolename:null};

values.forEach(function(v) {

if( == null) { =;}

if(outs.rolename == null) {outs.rolename = v.rolename;}


return outs;


  • Now time to apply map reduce over the collection to be joined.

> db.users.mapReduce(map,reduce,{out:’result_coll’})

  • Now result of join will be stored in result_coll, to check the output you can query result_coll.

> db.result_coll.find()


www to non www htaccess redirect

 Non www to www: To redirect the http requests for to, you should set the following rewrite rule. You should add the following lines at the beginning of the .htaccess file in your public_html folder or htdocs folder or whatever root folder your site is at – RewriteEngine On Options +FollowSymlinks -Multiviews RewriteCond […] Continue reading →

Mysql slow query log

 Why to enable slow query log? If your site started performing slow, then it is right time to analyse your mysql queries before situtation gets worst and your application gets down even with a minimal traffic. You can analyse queries that are performing slow and exhausting your CPU by enabling slow query logs in mysql. […] Continue reading →