Java & MongoDB - Overview



MongoDB developer team has provided MongoDB Driver for Java and have various resources available for it.

First step in connecting to MongoDB using Java is to have mongodb driver in the java classpath and then use mongodb API to connect to the database.

Connecting to MongoDB database

Suppose, MongoDB is installed locally and using default port then following syntax connects to MongoDB database.

MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");

As MongoClient assumes various default, it can be used using the following way as well.

MongoClient mongoClient = MongoClients.create();

Creating/Connecting to Database

Once mongoClient is instantiated, its getDatabase() method can be used to get connection to a database.

MongoDatabase database = mongoClient.getDatabase("myDb"); 

In case database is not present then above command will create the same.

In subsequent chapters, we'll see the various operations on MongoDB using Java.

Advertisements