All stories
Java

Connecting to Mongo DB

H
hemant-kumar

July 23, 2012


Starting up Database Server (mongod.exe)

Step 1: Download the “mongod.exe” binary.

Step 2: Extract it.

Step 3: Open Command prompt.

Step 4: Traverse to the folder containing the “mongod.exe” binary.

Step 5: Now type:  mongod --dbpath <database path>

Here database path is database directory path where we want to store our databases and it must physically exist.
Example:  mongod --dbpath E:\MongoDB

Now our database server has started on local host on port: 27017

Connecting to Database Server using Interactive shell (mongo.exe)

Step 1: Make sure that Database server is started.

Step 2: Open Command prompt.

Step 3: Traverse to the folder containing the “mongo.exe” binary.

Step 4: Now type:   mongo --host <host address> --port <port no>

Here host address and port no is the address and port on which database server is running.
Example:   mongo --host 127.0.0.1 --port 27017

Now our shell is connected to database server.

Note: By default it is connected to test database.

In order to fetch the names of currently existing databases type:
show dbs

Connecting to Database Server using Java

Also fetch the names of currently existing databases type:

public static void main(String[] args) throws Exception
{
Mongo mongo = new Mongo("127.0.0.1",27017);
for(String databse : mongo.getDatabaseNames())
System.out.println(databse);
}


Download and add mongo.jar to your classpath.

Java

0

If you found this helpful, give it some claps!

SHARE THIS ARTICLE

Share on X
LinkedIn

Responses0

Sign in to join the conversation

Sign in