Mongodb with Java
First question comes in mind , what is mongodb ?
MongoDB is a document database that provides high performance, high availability, and easy scalability. It comes under NoSQL database family.
I will explain the advantage of mongodb database over RDBMS database later.
Here we will try to understand how to Integrate mongodb with java.
Step 1. MongoDB Java Driver Download
Add maven dependency for mongodb.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>
Step 2. Create Mongodb connection
MongoClient mongoClient = new MongoClient(); //connects to default host and port i.e 127.0.0.1:27017
// or
MongoClient mongoClient = new MongoClient( "localhost" ); //connects to default port i.e 27017
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // should use this always
// or, to connect to a replica set, with auto-discovery of the primary
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
Step 3. Connect to Mongodb database
DB db = mongo.getDB("mongoTest");
Step 4. Create Collection
DBCollection col = db.getCollection("testCollection");
If the collection doesn’t exist, MongoDB will create it for you. All the data in MongoDB goes into some collection, so at this point we are ready to perform insert/update/delete operations.
First question comes in mind , what is mongodb ?
MongoDB is a document database that provides high performance, high availability, and easy scalability. It comes under NoSQL database family.
I will explain the advantage of mongodb database over RDBMS database later.
Here we will try to understand how to Integrate mongodb with java.
Step 1. MongoDB Java Driver Download
Add maven dependency for mongodb.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>
Step 2. Create Mongodb connection
MongoClient mongoClient = new MongoClient(); //connects to default host and port i.e 127.0.0.1:27017
// or
MongoClient mongoClient = new MongoClient( "localhost" ); //connects to default port i.e 27017
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // should use this always
// or, to connect to a replica set, with auto-discovery of the primary
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
Step 3. Connect to Mongodb database
DB db = mongo.getDB("mongoTest");
Step 4. Create Collection
DBCollection col = db.getCollection("testCollection");
If the collection doesn’t exist, MongoDB will create it for you. All the data in MongoDB goes into some collection, so at this point we are ready to perform insert/update/delete operations.
Learn Mongodb with Java and maven.
ReplyDelete