Tuesday, 20 January 2015

Basic Commands

Now that u have a running Mongodb, i will start off with some very basic commands
If u haven't installed it yet, see the steps here

1. db;
this shows the database currently selected. since we haven't created any db it returns test, which is present by default.

2. show dbs or show databases;
This shows the list of all db's present in your system.

3. use dbname;
In Mongodb, there is no need to create a db before using it.By using this command mongo searches for the db. If the db is not found, it creates one and switches to that db.

4. db.dropDatabase():
Drops the database currently selected.

5. show collections;
This shows all the collections present in the db.

6. db.collectionname.insert():
If the collection name is not found,it creates a collection, else it inserts into the collection.
We pass the JSON document as the argument for the insert function.

example:
db.test1.insert({"name":"ravi","country":"India"});
db.test1.insert({"name":"saketh","interests":["chess","coding"]});
we can also insert documents inside a document like
db.test1.insert({name:"harry",age:17,address:[{school:"hogwarts"},{home:"godricks hollow"}]}); 
7. db.collectionname.find():
This shows all the documents inside a collection.

example: db.test1.find()

{ "_id" : ObjectId("54bf453f22fc6eaa4507787a"), "name" : "ravi","country":"India" }
{ "_id" : ObjectId("54bf48b022fc6eaa4507787b"), "name" : "saketh", "interests" : [ "chess", "coding" ] }
{ "_id" : ObjectId("54bf4d4e22fc6eaa4507787c"), "name" : "harry", "age" : 17, "address" : [ { "school" : "hogwarts" }, { "home" : "godricks hollow" } ] }

if we add pretty() command at the end of the find(), the shell shows the data in proper hierarchical manner, like

db.test1.find().pretty()

{
        "_id" : ObjectId("54bf453f22fc6eaa4507787a"),
        "name" : "ravi",
        "country":"India"
}
{
        "_id" : ObjectId("54bf48b022fc6eaa4507787b"),
        "name" : "saketh",
        "interests" : [
                "chess",
                "coding"
        ]
}
{
        "_id" : ObjectId("54bf4d4e22fc6eaa4507787c"),
        "name" : "harry",
        "age" : 17,
        "address" : [
                {
                        "school" : "hogwarts"
                },
                {
                        "home" : "godricks hollow"
                }
        ]
}








Collections and Documents

If you are from a relational background, then you know that data is stored in the form of tables, which has rows and columns .
However in MongoDB, data is stored in the form of collections which is equivalent to tables in MYSQL.
There are no rows and columns as in relational, but data is stored in the form of documents.
The data format of MongoDB is very much inspired from the JSON format which is used in JavaScript, where data is stored in the form of key value pairs.
So to compare,
Tables-Collections
Rows and columns- Documents

Here is a sample of how data is stored in JSON format
{
        "Name" : "Harry"
        "Student_id" : "Bgl14cj001",
        "Type" : "exam",
        "Score" : 54.6
}

The above data inside the curly braces is called a "Document".
Each key-value pair inside a document is separated by a comma(,).
Set of many such Documents is called a "Collection"

However in MongoDB, data is stored in BSON format( Binary JSON) format, i.e., data is stored in binary form inside DB. To know the complete set of Datatypes which BSON supports refer  http://bsonspec.org/

We can also hold array values for a key value pair, like
{
        "_id" : "Ethan",
        "Student_id" : "Bgl14cj001",
        "Type" : "exam",
        "Score" : 54.6,
        "Interests" : ["Chess","Badminton","Painting"]
}

Like in JSON, documents can also hold another document in a key-value pair
For example:

{
"_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
"name" : "MongoDB",
"notes" : [
    {
        "title" : "Hello MongoDB",
        "content" : "Hello MongoDB"
    },
    {
        "title" : "ReplicaSet MongoDB",
        "content" : "ReplicaSet MongoDB"
    }
]
}


Here, you can see that "notes" hold 2 documents as an array, an herein lies the true power of Mongodb.
We can hold any number of data inside a single document  and each data can be nested.

The key difference between structured and Unstructured is as i have explained before, the Schema-less nature.
That means each document can have its own structure like

{
        "_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
        "Name" : "Harry",
        "Type" : "exam",
        "Score" : 54.6,
        "Interests" : ["Chess","Badminton","Painting"]
}
{
        "_id" : ObjectId("4f7ee46e08403d063ab0b4d3"),
        "Name" : "Jenny",
        "pincode" : 500231
}

and This is valid!!

If u have observed carefully, each document has a field called "_id", which is holding either a hexadecimal format ObjectId or a predefined value such as "Ethan".

This _id field is more like the primary key in a relational database which uniquely identifies a particular document in the db.

More on _id field:
This _id field is automatically generated by Mongodb when creating a document.However, we can override it by our key by assigning a value while creating a document. I will discuss this afterwards on the creating documents section.

_id is a 12 byte hexadecimal value.In This first 4 bytes are for the current time stamp, next 3 bytes are for machine id, next 2 bytes for process id of Mongodb server and remaining 3 bytes are simple incremental value

Basic mongodb commands



Friday, 16 January 2015

installing MongoDB

First download  MongoDB
Select the suitable version for your system. 
Download either .zip or .msi, msi handles everything automatically 
install into a  folder

Getting Started:

If u go into the bin folder of the mongodb u'll find a lot of executable files
some of notable ones are
1.mongod
2 mongo
3 mongostat
4 mongoimport
5 mongodump
6 mongoexport   and so on....

we are gonna explore each of these as we proceed


For windows users
to start mongodb
1. open ur cmd(windows+R then type cmd and hit enter)
2. then go to the bin directory in cmd using shell commands(cd , cd.. ,cd\ and so on )
3. then type mongod --dbpath (urdbpath)

mongod handles data requests, manages data format, and performs background management operations
So by this command(mongod --dbpath) u are telling the mongodb to store ur database in a specific folder
For example i am storing my database in D:\test\mongodb\data. So my command will be
mongod --dbpath D:\test\mongodb\data

If the command is correct u should see various info printed like version number, your system properties and so on.

4. open another cmd
    go to the bin folder as done above
    then simply type mongo.exe
    you are in the mongo shell now!!!

To test if u are sucessfully connected, just type in  db;
if this returns "test" onto the shell, everything is woking properly!!

We need both the instances of cmd(mongod and mongo)simultaneously for working













Tuesday, 13 January 2015

Intoduction to MongoDB

What is MongoDB?

The term Mongo comes as a part of the word humongous , which means as huge and gigantic.
Technically mongodb comes under the category  of the databases called NOSQL which has been gaining lot of popularity in the recent times due to advance in Big data and other unstuctured database paradigms.

Why MongoDB?

The recent growth of these NOSQL databases is due to the data explosion and the inefficiency of the structured databases to hold the dynamic and unstuctured data.
When people designed MYSQL(around 20-30 yrs back), data storage was a issue and therefore the databases were built around that aspect.
But that is not the case now, where we have Terabytes of data cheaply and so, these modern databases are now focused on *performance*.

so, what aspects are under this performance?

1. Dynamic schema: In structured databases, if we were to add a column to a already existing database, we would have to do it by a very costly ALTER command, which is both time consuming and painstaking.

For designing a  MYSQL database we would need the architects to discuss at length, considering all the possibilities, and then proceed. But this is not suitable for the modern Agile development models where we keep updating as per the requirement

2. Data duplication: As i have mentioned earlier that structured databases have been designed for least data space, data duplication is not seen. This means that the data is stored at a centralized location and everyone has to access from the same. There is always a chance for data corruption or data loss in any system, which is a risky game

But in MongoDB there is option for data duplication, i.e same data is stored at various data centres

3. Access Speed: The access time for Mongo is many times faster than MYSQL, since in the later data has to be accessed from many tables by joining them.

Does this mean MongoDB can completely replace structured databases?

There is a tradeoff for all the better features provided and that is
There is NO rollback and other TCL(transaction control) commands as in MYSQL. So if your queries include many transactions at a time, it is better to use MYSQL

now lets get started with working of mongodb!!!

installing MongoDB