MongoDB for MySQL/RDBMS Developers : Part 1

This is my for first post for “Mongodb for Mysql developers series”. I come from RDBMS background and these were things which were new to me:

MySQL           -       MongoDB

"Database"	-	"Database"
"Tables"	-	"Collection"
"Row"		-	"Document"
"Columns"	-	"Fields"
"Join"		-	"Ain't no Joins in Mongo"
"Schema"	-	"Ain't no schema in Mongo. It's schemaless."

1. How do you login ?

MySQL 	:	mysql -u username -p databasename	//databasename is optional and once you hit enter it will prompt you for password
MongoDB	:	mongo					//Why no password ? Authentication is turned off by default. Explained later

2. Add a user in mongo

First of all you will need to add a user in mongo because by default you are connected as test user. This is how you do it.

db.addUser("mongosampleuser","somepassword")		//Give username and password.
db.addUser("mongosampleuser","somepassword",true)		//It will add a readonly user for you. 3rd parameter "true" will make it read-only
In both of the above case you will get an output like this :
"user" : "mongosampleuser",
"readOnly" : false,
"pwd" : "2a8025f0885adad5a8ce0044070032b3",
"_id" : ObjectId("52b540c36ac6d2254ec0e83c")

Now authenticate yourself :

db.auth("mongosampleuser","somepassword")		//Supply your username/password. It should return success.

3. How do you login as a user in mongo ?

mongo <hostname>:<port>/<database name> -u <username> -p <password>
e.g.: mongo localhost:27017/admin -u mongosampleuser -p somepassword	// you will be connected to admin database

4. Added a user but mongo didn’t ask for password.

It happens because mongo server is configured by default not to ask for password. You should change config of your mongo server to ask for password :

sudo /etc/init.d/mongodb stop	// Stop mongo instance

sudo vi /etc/mongodb.conf 	// Now set auth = true. Save and exit. I was using ubuntu 12.10 please check your location

sudo /etc/init.d/mongodb start	//

mongo localhost:27017/admin -u mongosampleuser -p somepassword	// you will be connected to admin database

5. List all database please ?

MySQL :  show databases;
Mongo :  show dbs;

6. How shall i change my database ?

MySQL :  use databasename;
Mongo :  use databasename;

7. How do i know which database am i connected to ?

MySQL 	:	status;		// look for string like "Current database:	databasename" in output
MongoDB	:	db.getName();

8. How do you list all tables ?

MySQL 	:	show tables;
MongoDB	:	show collections;

I wrote this post because i had to google for every single command when i was learning. Hope it helps. I will be writing more on MongoDB in my next post.