MongoDB (named from "huMONGOus," meaning "extremely large")
MongoDB is an open source NoSQL database, which store data in form of BSON(Binary JavaScript Object Notation) documents which makes MongoDB to have dynamic schema and the integration of data in certain types of applications easier and faster.
MongoDB with Java
MongoDB is an open source NoSQL database, which store data in form of BSON(Binary JavaScript Object Notation) documents which makes MongoDB to have dynamic schema and the integration of data in certain types of applications easier and faster.
MongoDB with Java
Yet another database, which is a NoSQL database. Okay, first you download it from http://www.mongodb.org/downloads and hey don’t forget download JDBC driver from https://github.com/mongodb/mongo-java-driver/downloads .
Now I just tried to map MongoDB basic concepts with SQL.
SQL | MongoDB |
Schema | Database |
Table | Collection |
Row | Document |
Column | Field |
Index | Index |
Joining | Embedding & Linking |
Now we will try to create a collection in database.
Get Started
Now try to develop some sample programming with the help of mongoDB Java driver. Now start the the mongoDB server and include mongoDB Java driver into your classpath.
Now try to get connection
It is easy to create connection using com.mongo.Mongo class, if MongoDB run on local machine.
Mongo newConn = null;
newConn = new Mongo();
or
newConn = new Mongo(“localhost”);
or
newConn = new Mongo(“localhost”,27017); // 27017 is default port
Above code by default connect to localhost in 27017 port.
Create a collection
package com.mongoDB.test;
import java.net.UnknownHostException;
import java.util.List;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteResult;
class Address extends BasicDBObject {
public Address(){
}
public Address(String name,String street,int zipcd) {
put("name", name);
put("street",street);
put("zipcd",zipcd);
}
}
public class CreateCollection {
public static void main(String[] args) {
Mongo dbConnection = null;
try {
//Create a connection
dbConnection = new Mongo();
/*
* dbConnection = new Mongo("localhost");
* dbConnection = new Mongo("localhost",27017);
* */
DB db =dbConnection.getDB("mydb");
// Creating a database object
Address address = new Address("Testing1","Local Street",123456);
// Creating a database collection (Table)
// db.collectionExists("address") check whether this collection exist or not
// db.getCollection("address") return collection if exist
// db.createCollection("address", address) create a collection
DBCollection dbCollection = db.collectionExists("address")?db.getCollection("address"):db.createCollection("address", address);
// dbCollection.save(address) save the document into collection
dbCollection.save(address);
//select all from 'address' collection
DBCursor dbcur = dbCollection.find();
// check any document is there or not
while(dbcur.hasNext()){
// get the document
DBObject dbObj = dbcur.next();
System.out.println(“\nName = ”+dbObj.get("name")+” Street = ”+dbObj.get("street")+” ZIP CODE = “+dbObj.get("zipcd"));
}
}catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MongoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Insert a document
We already know how to get collection object. Now insert a document into a collection.
In JSON this document represented as
{
"phoneNumber" : NumberLong("99012233123"),
"phoneNumberType" : "Mobile",
"personId" : {
"id" : "1232325",
"idType" : "SSN"
},
"name" : {
"firstName" : "Fname",
"middleName" : "Mname",
"LastName" : "Lname"
},
"address" : {
"street" : "Street",
"city" : "City",
"zipcd" : "123256"
}
}
Here personId,name,address are inner document. To insert a document we can use BasicDBObject and BasicDBObjectBuilder.
BasicDBObject This class object hold a document in key value pair. Multiple object of this class means multiple documents whether it will be a inner document it depends
BasicDBObject name = new BasicDBObject();
name.put("firstName", "Fname");
name.put("middleName", "Mname");
name.put("LastName", "Lname");
BasicDBObjectBuilder This class is similar like StringBuilder, simply create an object using BasicDbObjectBuilder.start() and append key value pair. Here is a point to note add(String,Object) and append(String,Object) both are same add method invoke append method. So there is no difference in using either.
BasicDBObjectBuilder address = BasicDBObjectBuilder.start();
address = address.add("street", "Street");
address = address.add("city", "City");
address = address.add("zipcd", "123256");
package com.mongoDB.test;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import org.bson.BSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
public class InsertDocument {
public static void main(String[] args) {
Mongo dbConn = null;
try {
dbConn = new Mongo("localhost",27014);
DB db = dbConn.getDB("mydb1");
char[] passwd = {'p','a','s','s','w','o','r','d'};
// Authenticating user
if(!db.authenticate("user", passwd)){
return;
}
DBCollection dbCollection = db.getCollection("mycoll");
BasicDBObject personDemographic = new BasicDBObject();
/ * name:{"firstName":value,
* "middleName":value,
* "LastName":value}
* */
BasicDBObject name = new BasicDBObject();
name.put("firstName", "Fname");
name.put("middleName", "Mname");
name.put("LastName", "Lname");
/* address : {
* street : value,
* city : value,
* zipcd : value }
**/
BasicDBObjectBuilder address = BasicDBObjectBuilder.start();
address = address.add("street", "Street");
address = address.add("city", "City");
address = address.add("zipcd", "123256");
String personIdStr = "{'id' : '1232325','idType' : 'SSN'}";
//parse it as a JSON String
DBObject personId = (DBObject)JSON.parse(personIdStr);
BSONObject phoneNo = new BasicDBObject();
phoneNo.put("phoneNumber", 99012233123L);
phoneNo.put("phoneNumberType", "Mobile");
Map<String,DBObject> dbObjMap = new HashMap<String,DBObject>();
dbObjMap.put("name", name);
dbObjMap.put("address", address.get());
dbObjMap.put("personId", personId);
personDemographic.putAll(phoneNo);
personDemographic.putAll(dbObjMap);
dbCollection.insert(personDemographic);
DBCursor dbCurr = dbCollection.find();
while(dbCurr.hasNext()){
System.out.println(dbCurr.next().toString());
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
Output
{ "_id" : ObjectId("4fe1afb46361e48f9f01bf5c"), "phoneNumber" : NumberLong("99012233123"), "phoneNumberType" : "Mobile", "personId" : { "id" : "1232325", "idType" :
"SSN" }, "name" : { "firstName" : "Fname", "middleName" : "Mname", "LastName" : "Lname" }, "address" : { "street" : "Street", "city" : "City", "zipcd" : "123256" } }
Update a document
Lets update a document. We can use methods like update, updateMulti and findAndModify to update a document. Among these methods update method is overridden & updateMulti method internally call update method not only that even save method internally call update method.
One update method which is called every time you call any update api.
public WriteResult update( DBObject query , DBObject o , boolean upsert , boolean multi , com.mongodb.WriteConcern concern, DBEncoder encoder );
query - takes DBObject as a query
o - take DBObject which will be replaced with new object
upsert - if the database should create a new document if it is not there
multi - if all matching document will be updated or not. An object will not be inserted if it does not exist in the collection and upsert=true and multi=true. See http://www.mongodb.org/display/DOCS/Atomic+Operations
concern - the write concern
encoder - DBEncoder to be used
package com.mongoDB.test;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
public class UpdateDocument {
public static void main(String[] args) {
Mongo dbConn = null;
try {
dbConn = new Mongo();
DB db = dbConn.getDB("mydb1");
DBCollection dbCollection = db.getCollection("mycoll");
// Object to be quered
DBObject query = new BasicDBObject();
query.put("phoneNumber", 99012233123L);
// Object to be replaced
DBObject replaced = new BasicDBObject();
replaced.put("phoneNumber", 98012233123L);
dbCollection.update(query, new BasicDBObject().append("$set", replaced), false, false);
// Query for find
query.put("phoneNumber", 98012233123L);
DBCursor dbCur = dbCollection.find(query);
while(dbCur.hasNext()) {
System.out.println(dbCur.next());
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
Output
{ "_id" : { "$oid" : "504354ebf090ca58102e6523"} , "address" : { "street" : "Street" , "city" : "City" , "zipcd" : "123256"} , "name" : { "firstName" : "Fname" , "middleName" : "Mname" , "LastName" : "Lname"} , "personId" : { "id" : "1232325" , "idType" : "SSN"} , "phoneNumber" : 98012233123 , "phoneNumberType" : "Mobile"}
The information which you have provided in this blog is really useful to everyone. Thanks for sharing.
ReplyDeleteMean Stack Online Training
Mean Stack Training in Hyderabad