MongoDB using Java

This tutorial is the quick introduction of MongoDB with java:-

What is MongoDB?

MongoDB is a very popular NoSql open source database. It works on collection rather than table and document rather than row and column. It facilitates high performance, high availability, and easy scalability.

MongoDB stores data in flexible, JSON-like documents, whese fields can vary from document to document and data structures can be changed over time.

The document model maps to the objects in your application code, making data easy to work with.

Sample Example:
{
"rollNumber":1,

"firstName":"Prakash",

"lastName":"Pandey"
}

Prerequisites:-

Download and Install MongoDB Community Server 

Download and Install MongoDB Compass 

Download Java-Driver-Server Mongo-java-driver-3.12.3.jar and copy to C://MongoDB folder

Download latest version of JDK


How to run MongoDB Server:-

Create a folder C:\data\db 

Move to C:\Program Files\MongoDB\Server\4.2\bin 

then there Execute mongod


Establishing a Connection with MongoDB:-

Use MongoClient() to make a connection with a running MongoDB instance.

The MongoClient instance represents a pool of connections to the databases, you will only
need one instance of class MongoClient even with multiple threads

Specify the Hostname and the Port:

MongoClient mongoClient=new MongoClient("localhost",27017);


Accessing Database:-

Now for Connecting with the database once you have a MongoClient instance Connected to a MongoDB deployment, use the MongoClient.getDatabase() method to access a database.

Specify the name of the database to the getDatabase() method. If a database does not exist, MongoDB
creates the database when you first store data for that database.

DB db=mongoClient.getDB("School");


Accessing a Collection:-

Now create a collection which is equivalent to a table in RDBMS.

Once you have a MongoDataBase instance, use its getCollection() method to access a
collection.

Specify the name of the collection to the getCollection() method. If a collection does not exist,
MongoDB creates the collection when you first store data for that collection.

For example, using the database instance, the following statement retrives the collection 
named students in the School database

DBCollection students=db.getCollection("students");


Now let’s start the implementation of mongo query with java, We will start with CRUD operations. 1.Insert
2.Update
3.Find
4.Delete

Insert:-

Once you have the MongoCollection instance, you can insert documents into the collection.

To insert a document into the collection, you can use the collections insert() method.

eg1.java

import com.mongodb.*;
class eg1psp
{
public static void main(String gg[])
{
MongoClient mongoClient=new MongoClient("localhost",27017);
DB db=mongoClient.getDB("School");
DBCollection students=db.getCollection("students");
BasicDBObjectBuilder objectBuilder;
objectBuilder=BasicDBObjectBuilder.start();
objectBuilder.append("rollNumber",101);
objectBuilder.append("firstName","Prakash   ");
objectBuilder.append("lastName","Pandey");
DBObject document=objectBuilder.get();
students.insert(document);
mongoClient.close();
System.out.println("Done");
}
}

Compile:- javac -classpath c:\mongodb\*;. eg1.java
Run:- java -classpath c:\mongodb\*;. eg1psp

If you want to Insert a single document into the collection, you can use the collections insertOne() method.

For example:-
collection.insertOne(document);


Update:-

To update documents in a collection, you can use the collections update methods.

Firstly search document where old data is stored in the collection and update it with new values
for example:- we have the following document

{
"rollNumber":1,

"firstName":"Prakash",

"lastName":"Pandey"
}

we need to Update firstName "Prakash" to "Ram"

eg2.java

import com.mongodb.*;
class eg2psp
{
public static void main(String gg[])
{
MongoClient mongoClient=new MongoClient("localhost",27017);
DB db=mongoClient.getDB("School");
DBCollection students=db.getCollection("students");
BasicDBObjectBuilder documentBuilder;
documentBuilder=BasicDBObjectBuilder.start();
documentBuilder.append("rollNumber",101);
documentBuilder.append("firstName","Ram");
documentBuilder.append("lastName","Pandey");
DBObject document=documentBuilder.get();
documentBuilder=BasicDBObjectBuilder.start();
documentBuilder.append("_id",101);
DBObject queryobject=documentBuilder.get();
students.update(queryobject,document);
mongoClient.close();
System.out.println("done");
}
}

Compile:- javac -classpath c:\mongodb\*;. eg2.java
Run:- java -classpath c:\mongodb\*;. eg2psp

Update a Single Document, use the updateOne(queryobject, document)


Find all documents in a collection:-

To retrieve all the documents in the collection, we will use the find() method without any 
parameters. 

To iterate through the results, chain the iterator() method to the find()

If you want to Specify a Filter:- pass a filter object to the find() method.

eg3.java

import com.mongodb.*;
class eg3psp
{
public static void main(String gg[])
{
MongoClient mongoClient=new MongoClient("localhost",27017);
DB db=mongoClient.getDB("School");
DBCollection students=db.getCollection("students");
DBCursor cursor=students.find();
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
mongoClient.close();
System.out.println("DONE");
}
}

Compile:- javac -classpath c:\mongodb\*;. eg3.java
Run:- java -classpath c:\mongodb\*;. eg3psp

To Find the First Document in a Collection, use the find() method without any parameters and chain to find() method the first() method. 

If the collection is empty, the operation returns null.

Count Documents in A Collection, use the collections count() method. 


Delete:-

 To delete documents from a collection, you can use the collections remove methods. 

Pass a query object ,to the methods a filter object to determine the document or documents to delete. 

To specify an empty filter (i.e. match all documents in a collection), use an empty Document object.

eg4.java


import com.mongodb.*;
class eg4psp
{
public static void main(String gg[])
{
MongoClient mongoClient=new MongoClient("localhost",27017);
DB db=mongoClient.getDB("School");
DBCollection students=db.getCollection("students");
BasicDBObjectBuilder documentBuilder;
documentBuilder=BasicDBObjectBuilder.start();
documentBuilder.append("_id",101);
DBObject document=documentBuilder.get();
students.remove(document);
mongoClient.close();
System.out.println("Done");
}
}

Compile:- javac -classpath c:\mongodb\*;. eg4.java
Run:- java -classpath c:\mongodb\*;. eg4psp

Delete a Single Document That Match a Filter, use the deleteOne method:


Hope this was helpful.

Thank you:-

Comments

Post a Comment

Popular posts from this blog

MongoDB using C

Lambda Expression in Java

Designing the Buyer Centric Funnel