Friday, 10 April 2020

How To Use MongoDB with Java Application .

What is Mongo Database ?


MongoDB is a No SQL database. It is an open-source, cross-platform, document-oriented database written in C++;

What is No SQL ?

It provides a mechanism for storage and retrieval of data other than tabular relations model used in relational databases. NoSQL database doesn't use tables for storing data. It is generally used to store big data and real-time web applications.


MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling.

In simple words, you can say that - Mongo DB is a document-oriented database. It is an open source product, developed  in 2007 and supported by a company named 10gen also known as MongoDB Inc.

Advantages of NoSQL

It supports query language.
It provides fast performance.
It provides horizontal scalability.

Basic Terminology Of MongoDB

Document:- MongoDB is a document database: each record in a MongoDB collection is document. Documents are a structure composed of file and value pairs, similar to JSON objects or other mapping data types.
Example:-
{
  "empId": 1,
  "name": "JK",
  "company";"10gn"
  }

Collection :- A Collection is collection MongoDB documents . 

Database :- A Database is MongoDB collection . 

Mongo DB with Java 

First install MongoDB on your Machine then  go to installation directory of MongoDB 
like on my machine it is .

C:\Program Files\MongoDB\Server\4.2
Then create a folder a name with db in data folder . after that to use mongoDB first start the 
MongoDB Server by following command .

Open Command prompt in bin directory of Server

C:\Program Files\MongoDB\Server\4.2\bin>mongod.exe --dbpath "C:\Program Files\MongoDB\Server\4.2\data\db"

To user MongoDB with Java Application first Download the MongoDB Server Driver jar

mongo-java-driver-3.3.0.jar  and put it on classpath of your java application .


How to create  and use database  and collection in MongoDB



package in.jk.mongo;

import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;

public class MongoCollectionApplication {

public static void main(String[] args) {


  MongoClient mongoClient = new MongoClient("localhost", 27017);
 // create a database or if database with given already exist use it .
MongoDatabase database = mongoClient.getDatabase("employeedata");
database.createCollection("samplecollection"); // create a new collection
MongoIterable<String>collectionNames=database.listCollectionNames();
Iterator<String> iterator=collectionNames.iterator();
System.out.println("All Collection Name ::");
while (iterator.hasNext()) {
String name = (String) iterator.next();
System.out.println(name);
}
System.out.println();
MongoCollection<Document> collections = database.getCollection("samplecollection");                    collections .drop();// drop a collection 
MongoIterable<String>collectionNames1=database.listCollectionNames();
Iterator<String> iterator1=collectionNames1.iterator();
System.out.println("All Collection Name ::");
while (iterator1.hasNext()) {
String name = (String) iterator1.next();
System.out.println(name);
}
mongoClient.close();

}

}

How  to insert a Document in  MongoDB 

package in.jk.mongo;

import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoApplication {

public static void main(String[] args) {

try {

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("employeedata");
// database.createCollection("empcollection"); // create a collection if not
// exist ..
MongoCollection<Document> collection = database.getCollection("empcollection");
Document document = new Document();
document.put("empId", 4);
document.put("name", "JK");
document.put("company", "10 Gen Inc");
collection.insertOne(document);
System.out.println("Document Save Succussfully .");
System.out.println();
MongoCollection<Document> collection database.getCollection("empcollection");
System.out.println("Size of Collection :: " + collection .count());
FindIterable<Document> findItr = collection .find();
MongoCursor<Document> cursor = findItr.iterator();
while (cursor.hasNext()) {
Document document2 = (Document) cursor.next();
System.out.println(document2);

}

mongoClient.close();

} catch (Exception e) {

System.out.println("Exception ::" + e);
}

}
}













How to update a Document in MongoDB
package in.jk.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class UpdateDocumentApplication {

public static void main(String[] args) {

try {

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("employeedata");
// database.createCollection("empcollection");
MongoCollection<Document> collection = database.getCollection("empcollection");
System.out.println("Size of Collection :: " + collection.count());
                        FindIterable<Document> findItr = collection.find();
                        MongoCursor<Document> cursor = findItr.iterator();
                        while (cursor.hasNext()) {
        Document document2 = (Document) cursor.next();
                        System.out.println(document2);

}
System.out.println();
MongoCollection<Document> collection1 = database.getCollection("empcollection");
collection1 .updateOne(Filters.eq("name", "JK"), Updates.set("name", "johny"));
System.out.println("After Update :: ");
System.out.println("Size of Collection :: " + collection1 .count());
                        FindIterable<Document> findItr1 = collection.find();
                        MongoCursor<Document> cursor1 = findItr1.iterator();
                        while (cursor1.hasNext()) {
Document document2 = (Document) cursor1.next();
                        System.out.println(document2);

}

mongoClient.close();

} catch (Exception e) {

System.out.println("Exception ::" + e);
}

}

}












How to Delete a Document in Mongo DB

package in.jk.mongo;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

public class DeleteDocumentApplication {

public static void main(String[] args) {

try {

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("employeedata");
MongoCollection<Document> collection = database.getCollection("empcollection");
System.out.println("Size of Collection :: " +collection.count());
FindIterable<Document> findItr = collection.find();
MongoCursor<Document> cursor = findItr.iterator();

while (cursor.hasNext()) {
Document document2 = (Document) cursor.next();
System.out.println(document2);

}

System.out.println();
MongoCollection<Document> collection1 = database.getCollection("empcollection");
collection1.deleteOne(Filters.eq("name", "johny"));
System.out.println("After Delete :: ");
System.out.println("Size of Collection :: " + collection.count());
FindIterable<Document> findItr1 = collection.find();
MongoCursor<Document> cursor1 = findItr1.iterator();
while (cursor1.hasNext()) {
Document document2 = (Document) cursor1.next();
System.out.println(document2);

}

mongoClient.close();

} catch (Exception e) {

System.out.println("Exception ::" + e);
}

}

}












No comments:

Post a Comment