Saturday, 31 October 2015

MongoDB Basics

Install MongoDB

First download the latest release of MongoDB. Make sure you get correct version of MongoDB depending upon your windows version. Link to download - click here

Install by double click on .exe downloaded file.
After the installation complete Open command prompt and execute below commands -

C:/>cd setup/mongodb/bin     ..press enter
C:/setup/mongodb/bin>mongod.exe --dbpath "C:/data"   ...press enter

This will show waiting for connections message on the console output indicates that the mongod.exe process is running successfully.[Server]

Now to run the MongoDB, you need to open another command prompt and execute below command
C:/setup/mongodb/bin>mongo.exe  ....press enter

MongoDB shell version: 3.0.7
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(8439b0165k56k433), "a" : 1 }
>

This will show that mongodb is installed and run successfully. [Client]

Next time when you run mongodb you need to issue only commands


Introduction: 

MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling. It is the need for an Object Relational Mapping (ORM) to facilitate development.

Collections:
MongoDB stores documents in collections. documents stored in a collection must have a unique _id field that acts as a primary key.

Documents:
A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents.

Example:
{
   "_id" : ObjectId("98a876324b7c8eb21818cd38"),
   "name" : {
      "fname" : "Krishna Kumar",
      "lname" : "Chourasiya",
      "city" : "Pune",
      "contact" : [ 1234567890, 0123456789 ]
   }
}



Fundamental Differences - MongoDB Vs RDBMS

The immediate and fundamental difference between MongoDB and RDBMS is the underlying data model. A relational database structures data into tables and rows, while MongoDB structures data into collections of JSON documents. JSON is a self-describing, human readable data format. Originally designed for lightweight exchanges between browser and server, it has become widely accepted for many types of applications.

JSON documents are particularly useful for data management for several reasons. A JSON document is composed of a set of fields which are themselves key-value pairs. This means each JSON document carries its own human readable schema design with it wherever it goes, allowing the documents to easily move between database and client applications without losing their meaning.

JSON is also a natural data format for use in the application layer. JSON supports a richer and more flexible data structure than tables made up of columns and rows. In addition to supporting field types like number, string, Boolean, etc., JSON fields can be arrays or nested sub-objects. This means we can represent a set of sophisticated relations which are a closer representation of the objects our applications work with. Using JSON documents in our database means we don’t need an object relational mapper between our database and the applications it serves. We can persist our data in the right form for our application.


Let’s dive into an example. Imagine I have an application dealing with information describing vehicle information including make, manufacturer, and category. My documents might look like this:
  {
    "_id" : ObjectId("398ba7691738025d11aab772"),
    "manufacturer" : "Porsche",
    "name" : "550 Spyder",
    "category" : [
        "kids",
        "male",
        "female"
    ]
  }
 
It’s pretty clear what this document describes, and I could easily unmarshall this into an object native to my chosen language. Notice also that the “category” field is an array of strings. The ability to support arrays is an especially helpful feature; it simplifies the way my application interfaces with the database and helps me avoid a complicated database schema. Consider the complexity of supporting a repeating group in a properly normalized table structure. To represent the same data object in a single table row would like like this:
PK | Name | Manufacturer | categories 123 | “550 Spyder” | “Porsche” | “kids,male,female”


MongoDB Supported Datatypes

MongoDB supports many data types whose list is as below:
  1. String : Most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid.
  2. Integer : This type is used to store a numerical value. Integer can be 32 bit or 64 bit depending upon your server.
  3. Boolean : This type is used to store a boolean (true/ false) value.
  4. Double : This type is used to store floating point values.
  5. Min/ Max keys : This type is used to compare a value against the lowest and highest BSON elements.(B-> Binary)
  6. Arrays : This type is used to store arrays or list or multiple values into one key.
  7. Timestamp : ctimestamp. This can be handy for recording when a document has been modified or added.
  8. Object : This datatype is used for embedded documents.
  9. Null : This type is used to store a Null value.
  10. Symbol : This datatype is used identically to a string however, it's generally reserved for languages that use a specific symbol type.
  11. Date : This datatype is used to store the current date or time in UNIX time format. You can specify your own date time by creating object of Date and passing day, month, year into it.
  12. Object ID : This datatype is used to store the document’s ID.
  13. Binary data : This datatype is used to store binay data.
  14. Code : This datatype is used to store javascript code into document.
  15. Regular expression : This datatype is used to store regular expression


Data Model Design

MongoDB data model has been designed in such a way that it always suits to application needs. The key consideration for the structure of your documents is the decision to embed or to use references.

Normalized data models

Normalized data models describe relationships using references between documents.
References provides more flexibility than embedding. However, client-side applications must issue follow-up queries to resolve the references. In other words, normalized data models can require more round trips to the server.

Embedded Data Models

With MongoDB, you may embed related data in a single structure or document. These schemas are generally known as “denormalized” models, and take advantage of MongoDB’s rich documents. Embedded data models allow applications to store related pieces of information in the same database record. As a result, applications may need to issue fewer queries and updates to complete common operations. Have a look to below example -

To interact with embedded documents, use dot notation to “reach into” embedded documents. See query for data in arrays and query data in embedded documents for more examples on accessing data in arrays and embedded documents.


Places to use Embedded Data Model


MongoDB Indexe Users

MongoDB Indexes support the efficient execution of queries. MongoDB must scan every document in a collection, to select those documents that match the query statement. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.

If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect. Indexes are special data structures that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.
Below diagram illustrates a query that selects and orders the matching documents using an index:

Diagram of a query that uses an index to select and return sorted results. The index stores ``score`` values in ascending order. MongoDB can traverse the index in either ascending or descending order to return sorted results. 


MongoDB - Advantages - Click Here

No comments:

Post a Comment

Monads in Scala

Monads belongs to Advance Scala   concepts. It  is not a class or a trait; it is a concept. It is an object which covers other object. A Mon...