Wednesday, December 14, 2011

MongoDB : Remote Access - Part 2

As stated in previous post on MongoDB, once installed, user can verify by opening shell & by typing mongo. It will by defualt connect with the table test (which is not a one you created obviously) like below if everything worked properly during installation.


MongoDB shell version: 1.4.3
Wed Nov 23 14:31:29 ***
connecting to: test
>


Before moving on to remote access, better to know few very basic commands to check what you really wants to know. Type show dbs which will show what are the existing databases. Then if you want to use existing one or new one type use dbname which will not create a database at the exact moment but on the fly if it does not exist. In mongodb table is considered a collection. Actually here, this is not exact same as the table in RDBMS but for clarity consider it is so. For to view all the collections in used database type show collections & to use one, type use collectionname. To view all the data inside of selected collection, type db.collectionname.find(). Here in mongodb, once you selected a database, when querying with collection you always has to use the reference of the database with query. That is why you have to use db.$what_ever_the_bla_bla next. You can find sql to mongodb mapping relationship page here. 


Now let's move to setting up a remote connection to a mongodb server.  It is better to have two terminals. One to start server & listening on incoming requests. Second to locally execute & view whether remote calls have worked (optional).

To start server

1. Create a directory structure in root
sudo mkdir -p  /data/db
2. Grant user permission to it
sudo chown `id -u` /data/db

3. Run mongo server to listen on incoming connections
mongod
You will noticed that sever is starting & saying it is listening on port as indicated in below image.
 
But If the result is like below

Then do the following.

4. Find mongodb PID & kill it.
ps -eF | grep 'mongo\|PID'

 
5. You can see in first shell image, I have executed this command & obtained the ID 1143. Next is to kill that process.
sudo kill “PID_VALUE”
Re-run the mongodb server: mongod
This is because if mongodb was installed using sudo apt get install, it will always run each time machine reboots. Therefore before server starts up, already running process has to be killed. Then server will start properly and keep on listening for incoming connections. To connect to a remote server simply type mongo remoteIPaddress after starting the mongodb server on both sides.To get mongodb execution status use sudo status mongodb


From now on there are plenty of enough resources available to continue with mongodb. Go after & enjoy the power of mongo.

No comments: