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
1,Mercedes,E-Class,12121,Red,12/12/2015,YES,1
2,Renault,Note,1223,Blue,09/09/2014,NO,2
3,Daihatsu,Terios,2333,Gray,10/10/2010,NO,2
4,BMW,S3,3988,Black,05/10/2008,YES,1


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:
 db.cars.count()    
To retrieve the count of the rows in this collection.
 db.cars.find()
To select all cars records
 db.cars.find({"Level":1,"Color":"Black"})
To select cars with level 1 and color is black.
 db.cars.find({"Price":{$gt:2000}})
To select cars with price more than 2000.
 db.cars.find({"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.
 db.cars.find({"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 :
db.cars.insert({ "_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:
db.cars.update({_id:6},{$set:{"Price":5432}})
To delete a row in the collection use:
db.cars.remove({"_id":5})
To drop the whole collection: (don't execute it now)
db.cars.drop()To analyze a query performance we can execute explain plan as following:
db.cars.find({"Color":"Red"}).explain()
We can create index to speed up the query by the following:
db.cars.ensureIndex({"Color":1}) 
This means we will create index for the Color field in ascending manner.
Re-execute: db.cars.find({"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)).
                sort(Sorts.ascending("Price"));
        iterable.forEach(new Block() {
            @Override
            public void apply(final Document document) {
                System.out.println(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 }";
db.getCollection("cars").insertOne(Document.parse(json));

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.








No comments:

Post a Comment