5 ways to connect to MongoDB

mongojava

I have been working on Mongo java 2.x driver , Recently we planned to update our Java driver version to 3.x.  Then i got realized that a lot has been changed.
Now lets start working on Mongo-Java-Driver 3.2 version.

Depenedency:

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>3.0.4</version>
    </dependency>
</dependencies>

Example Program:

Lets look at the different ways to connect to the mongoDB

public class ConnectToMongoDb {
    public static void main(String[] args) {

        // 1. directly connect to single local mongo server
        MongoClient mongoClient1 =  new MongoClient();

        //2. or
        MongoClient mongoClient2 =  new MongoClient("localhost");

        //3. connect to the local mongo server with specific port
        MongoClient mongoClient3 =  new MongoClient("localhost",27017);

        //4 connect to the mongo servers with auto discovery features
        MongoClient mongoClient4 =  new MongoClient(
                Arrays.asList(new ServerAddress("localhost", 27017),
                              new ServerAddress("localhost", 27018),
                              new ServerAddress("localhost", 27019)));

        //5 connect to mongo server using connection string
        MongoClientURI mongoClientURI =  new MongoClientURI("mongo://username:passowrd@localhost:27018/dbname");
        MongoClient mongoClient5= new MongoClient(mongoClientURI);

        MongoDatabase database = mongoClient1.getDatabase("databaseName");
    }
}

References:
http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/installation-guide/

Advertisements

About sivateja

I am a professional graduate..I am passionate about Latest Technology.
This entry was posted in mongodb and tagged , , , , . Bookmark the permalink.

One Response to 5 ways to connect to MongoDB

  1. Pingback: SivaPulse

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s