MongoDB and Java

This time, there is a rise of the NoSQL database. For a lot years, database has always been associated with SQL language, but there’s an emerging technology that does not uses SQL at all. Yes its a database that’s a form of simplified SQL. For example, NoSQL has:

1. No JOINS

2. Do not need to create tables to insert data.

3. JSON style storage

4. Using a lot of “.” annotation to query deep data.

MongoDB uses the following Data Models.

1. Embedded Data Models.

The models follow a JSON style format just like this.

{
 _id : 21
 user:
 contact: {
  phone: 212-345
  email: ahdn@example.com
 },
 access: {
  level: 1
  group: dev
 }
}

Above is a two layered embedded document, we can create this to 3 or 4 layers. Here’s an example of 3 layers. 1st layer is the “_id”, second is the “contact”, third is the “email”

{
_id : 21
user: abc
contact: {
 phone: 212-345
 email: {
  personal: ahdn@example.com
  office: ahdn@office.com
  },
 }
}

2. Normalized Data Models

below is an example of Normalized Data Models, which uses id for referencing.

=================================

{
 _id : 21
user: “abc”
}

{
_id : 1
 user_id: 21
level: 1
group: “dev”
}

{

_id : 1
user_id: 21
phone: “212-345”
email: “ahdn@example.com”
}

=================================

Integration with Java

( improved ! )

To use MongoDB in Java, it is needed to import ‘com.mongodb.*’ libraries. It can be downloaded here: https://github.com/mongodb/mongo-java-driver/downloads .

To use MongoDB, here are the steps what to include in the Java Class:

1. Install a running MongoDB

2. Create a connection to the Database. Use MongoClient Object.

example:  MongoClient mongoClient = new MongoClient( “localhost” );

2. Use DBCollection Object to insert a collection.

example: DBCollection collection = db.getCollection(“dummyColl”);

3. Use DBCursor Object to find the Document ( refers to the data set inserted )

example:

BasicDBObject document = new BasicDBObject();
        document.put(“database”, “testDB”);
        document.put(“table”, “hosting”);

collection.insert(document);

More references here:

http://blog.mongolab.com/2012/08/why-is-mongodb-wildly-popular/

http://www.tutorialspoint.com/mongodb/mongodb_java.htm

http://docs.mongodb.org/manual/core/data-model-design/

http://www.mkyong.com/mongodb/java-mongodb-insert-a-document/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s