Sunday, December 13, 2015

Simplified Guide To Use MongoDB

MongoDB is one of the No-SQL database engines, it is Document Oriented Database.
Documents can represent any structure that can fit JSON format so for example the following is a car document :
        "_id" : 6,
        "Car" : "BMW",
        "Model" : "S5",
        "Price" : 3455,
        "Color" : "Blue",
        "Date" : "09/10/2015",
        "Full Options" : "YES",
        "Level" : 1

Simplified Steps to use MongoDB:

1) Install the database locally...

Download it and install it.
From the command line execute: mongod and specify the location of the database files (any valid path so it can be used for storing database files).
mongod --dbpath c:\MongoDB\Database
All database command lines exist in the bin folder under Server directory.

2) Create any test data ..

You can create .csv file or .json file the simplest and quickest way is to use .csv file.
For example:
_id,Car,Model,Price,Color,Date,Full Options,Level

As you can see the _id is the primary key in MongoDB (if you didn't specify it, MongoDB will generate it for these entries.

3) Import test data

From the command line run the following commands:
mongoimport -d catalog -c cars --file cars.csv --type csv --headerline
This will import our file into Catalog database (similar to Schema in SQL DB) in a collection named cars (similar to DB table in SQL DB)
Note: if you import json file you don't need to specify the --type or --headline

 4) Manipulate MongoDB data 

Execute mongo from the command line ...
The default will connect to the localhost running instance ...
To connect to our database (schema) that we have created for cars, execute:
 use catalog
Now we can see all existing collections i.e. tables by executing:
 show collections
which will display only "cars" collection.
To deal with "cars" we can use the following:    
To retrieve the count of the rows in this collection.
To select all cars records{"Level":1,"Color":"Black"})
To select cars with level 1 and color is black.{"Price":{$gt:2000}})
To select cars with price more than 2000.{"Price":{$lte:3000},"Color":/l/}).pretty()
To select cars with price less than 3000 and color contain a "l" letter inside and then format it in JSON readable format.{"Price":{$gte:1000}}).sort({"Price":1}).skip(1).limit(2).pretty()
To select all cars with price more than or equal 1000 and sort the return by price ascending and limit the output to 2 only after skip the 1st results (we can use -1 to sort the result descending).
Note: You can use findOne() instead of find() to return the 1st match only.
To insert a new record :{ "_id" : 6, "Car" : "BMW", "Model" : "S5", "Price" : 3455, "Color" : "Blue", "Date" : "09/10/2015", "Full Options" : "YES", "Level" : 1 })
 To update the price of this inserted record we can use:{_id:6},{$set:{"Price":5432}})
To delete a row in the collection use:{"_id":5})
To drop the whole collection: (don't execute it now) analyze a query performance we can execute explain plan as following:{"Color":"Red"}).explain()
We can create index to speed up the query by the following:{"Color":1}) 
This means we will create index for the Color field in ascending manner.
Re-execute:{"Color":"Red"}).explain() to see the effect of this index.

5) Use MongoDB from inside Java Code

1- Add Mongo required drivers to your project classpath ...
 - mongodb-driver-3.0.4.jar
 - mongodb-driver-core-3.0.4.jar
 - bson-3.0.4.jar

2- Write your code to connect to the Database as following:
MongoClient mongoClient = new MongoClient();
This connect to a local running mongoDB on a default a port.
MongoDatabase db = mongoClient.getDatabase("catalog");
This connect to our catalog database.
FindIterable iterable = db.getCollection("cars").
                find(new Document("Level", 1)).
        iterable.forEach(new Block() {
            public void apply(final Document document) {

This query our cars collection for Cars with level 1 and sort them ascending by Price, iterate over the output and print each Document (i.e. JSON string).
 To insert an entry use the same way:
String json = "{ \"_id\" : 5, \"Car\" : \"Kia\", \"Model\" : \"Picanto\", \"Price\" : 777, \"Color\" : \"Blue\", \"Date\" : \"09/09/2011\", \"Full Options\" : \"NO\", \"Level\" : 3 }";

You can convert Bean objects into JSON and vice versa using any existing APIs..

This is simplified overview that covers most of MongoDB in nutshell and let you master how to deal with this database in just 5 minutes.