Java Data Base Connectivity (JDBC) with MongoDB
Lets first start with some basics of MongoDB.
What is MongoDB?
MongoDB is document-oriented NoSQL database. This is a collection of documents where data is stored in the form documents, unlike old SQL systems where data is stored in the form of tables. Here each document consists of the key-value pairs which are the building block of the NoSQL database. The data is stored in documents in the key-value pairs.
example:
{
"first_name":"Ambarish",So basically the data is stored in the JSON format called documents in MongoDB.
Now we are here to connect, create, access, and modify collections and documents of MongoDB using java. So let's get started. First of all, we will learn how to set up a MongoDB client driver for java. I am assuming that you have installed MongoDB on your system. If not then download and install it from this link: MongoDB.
Get MongoDB client driver:
In the C directory create a folder structure: C:\data\db. All the databases will be stored in 'db' folder by MongoDB.
Now we are all set to write our first code of creating a document in MongoDB using java.
Program 1: To create a database, collection, and document:
- Connect to MongoDB Server
First of all, connect to the MongoDB server. MongoDB server listens to
requests by default on 27017 port number. Here our host will be
localhost. To connect to the server we will create an object of
MongoClient class.
MongoClient mongoClient=new MongoClient("localhost",27017);
- Get the object of the database
To access the database we will call method getDB() and pass the name of
the database to this function of MongoClient class. It will return the
reference of DB class object. Here the database name you have passed if it does not exist then it
will create that database automatically.
DB db=mongoClient.getDB("testDB");
- Get collection from the database
Now get the collection in the database for this will call
getCollection() method of DB class and pass the name of collection and if the passed argument of name of collection does not exist then it will create that one in the
given database automatically.
DBCollection students=db.getCollection("students");
- Create a document object.
Now to create the document, create the object builder by calling static start() method of BasicDBObjectBuilder class, this method will return the address of this class.
BasicDBObjectBuilder objectBuilder = BasicDBObjectBuilder.start();
- Append key-value pair in the document object
Append the key-value pair for a document in the collection. Every
document in a collection must have a unique key with the name '_id' if
the user doesn't create one explicitly then MongoDB will create a unique
id implicitly. Code to append is as below:
objectBuilder.append("_id",id);
objectBuilder.append("firstName",firstName);
objectBuilder.append("lastName",lastName);
- Get the document
Get the instance of DBObject from Object builder.
DBObject document=objectBuilder.get();
- Insert the document in the collection.
With reference to the collection, insert the document in the
collection.
students.insert(document);
Now the complete code will look like this:
Example1.java
First of all, connect to the MongoDB server. MongoDB server listens to requests by default on 27017 port number. Here our host will be localhost. To connect to the server we will create an object of MongoClient class.
MongoClient mongoClient=new MongoClient("localhost",27017);
DB db=mongoClient.getDB("testDB");
DBCollection students=db.getCollection("students");
BasicDBObjectBuilder objectBuilder = BasicDBObjectBuilder.start();
objectBuilder.append("_id",id); objectBuilder.append("firstName",firstName); objectBuilder.append("lastName",lastName);
DBObject document=objectBuilder.get();
students.insert(document);
import com.mongodb.*; class Example1 { public static void main(String arg[]) { int id=111; String firstName="Ambarish"; String lastName="Dashora"; MongoClient mongoClient=new MongoClient("localhost",27017); DB db=mongoClient.getDB("testDB"); DBCollection students=db.getCollection("students"); BasicDBObjectBuilder objectBuilder=BasicDBObjectBuilder.start(); objectBuilder.append("_id",id); objectBuilder.append("firstName",firstName); objectBuilder.append("lastName",lastName); DBObject document=objectBuilder.get(); System.out.println(document); students.insert(document); mongoClient.close(); } }
To compile the above code we will have to specify the location in the classpath, where we have stored the jar file as discussed above.
To execute this program we must first make sure that the MongoDB server is running or not. If during installation you have checked the checkbox to run as service then your server will be running otherwise you will have to execute mongod.exe file located at the place where you have installed your MongoDB server in my case it is this :
"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe"
It is default installation location.
So now the server is running and you need to execute the program to insert a document in the collection. For this, we will type the following command:
java -classpath c:\location to the jar file Example1
So that's done we have finally inserted the document in the collection. As you can see we neither had testDB named database nor students named collection and both of them got created and the document got inserted in the collection after the execution of the above program.
Program 2: To get all the documents of a collection:
- Get the cursor object
To get all documents, we will call the find() method of
collection class through its reference. It will return the reference
of DBCursor class.
DBCursor cursor=students.find();
DBCursor cursor=students.find();
- Iterate and get all documents
Now with the reference DBCursor object we will call two methods
hasNext() which will return true or false i.e whether the next
document is present or not and next() which will return each document in
JSON form, these two methods will provide us all documents in the
collection.
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
Now the complete code will look like this:
Example2.java
while(cursor.hasNext()) { System.out.println(cursor.next()); }
import com.mongodb.*; class Example2 { public static void main(String ar[]) { MongoClient mongoClient=new MongoClient("localhost",27017); DB tmdb=mongoClient.getDB("testDB"); DBCollection st sudents=tmdb.getCollection("students"); DBCursor cursor=students.find(); while(cursor.hasNext()) { System.out.println(cursor.next()); } mongoClient.close(); } }
Program 3: To delete a document from the collection:
import com.mongodb.*; class Example3 { public static void main(String aa[]) { MongoClient mongoClient=new MongoClient("localhost",27017); DB db=mongoClient.getDB("testDB"); DBCollection students=db.getCollection("students"); BasicDBObjectBuilder objectBuilder=BasicDBObjectBuilder.start(); objectBuilder.append("firstName","binod"); DBObject query=objectBuilder.get(); students.remove(query); mongoClient.close(); } }
Program 4: To update a document in the collection:
import com.mongodb.*; class Example4 { public static void main(String a[]) { MongoClient mongoClient=new MongoClient("localhost",27017); DB db=mongoClient.getDB("testDB"); DBCollection students=db.getCollection("students"); BasicDBObjectBuilder documentBuilder=BasicDBObjectBuilder.start(); documentBuilder.append("_id",113); documentBuilder.append("firstName","Binod"); documentBuilder.append("lastName","Kumar"); DBObject document=documentBuilder.get(); BasicDBObjectBuilder queryBuilder=BasicDBObjectBuilder.start(); queryBuilder.append("_id",113); DBObject query=queryBuilder.get(); students.update(query,document); mongoClient.close(); } }
Very good content
ReplyDelete