Wednesday, 11 November 2015

MongoDB - CRUD operations

 The createCollection() Method

MongoDB db.createCollection(name, options) is used to create collection.

Syntax:

Basic syntax of createCollection() command is as follows
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection
Options like- capped, autoIndexID, size, max

While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

Examples:

Basic syntax of createCollection() method without options is as follows
>use krishnamongodb
switched to db krishnamongodb
>db.createCollection("homecollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections
>show collections
homecollection
system.indexes
 
Following example shows the syntax of createCollection() method with few important options:
>db.createCollection("homecol", { capped : true, autoIndexID : true, size : 3142800, max : 10000 } )
{ "ok" : 1 }
>
 

 
NOTE: 
In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
>db.homecollection.insert({"name" : "Krishna Kumar"})
>show collections
homecol
homecollection
system.indexes
>
 

The drop() Method

MongoDB's db.collection.drop() is used to drop a collection from the database.
Syntax:

Basic syntax of drop() command is as follows -

db.COLLECTION_NAME.drop()



Method - insert()

To insert data into MongoDB collection, you need to use MongoDB's insert() or save()method.

Syntax

Basic syntax of insert() command is as follows:
>db.COLLECTION_NAME.insert(document)

Example

>db.hcomecol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is NOSql database',
   by: 'Krishna Kumar Chourasiya',
   url: 'http://mongodbworkspace.blogspot.in/',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 1000
})
 
Here homecol is our collection name, as created in previous tutorial. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert document into it.
In the inserted document if we don't specify the _id parameter, then MongoDB assigns an unique ObjectId for this document.

_id is 12 bytes hexadecimal number unique for every document in a collection. 12 bytes are divided as follows:
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
To insert multiple documents in single query, you can pass an array of documents in insert() command.

NOTE

To insert the document you can use db.homecol.save(document) also. If you don't specify _id in the document then save() method will work same as insert() method. If you specify _id then it will replace whole data of document containing _id as specified in save() method.

Insert Boolean Data

While inserting boolean data, you need to make sure you are using proper boolean keywords like (true,false). It should always start from lower case not from capital case.

Example: 
db.UserCredential.insert({"flag":true}) WriteResult({ "nInserted" : 1 }) db.UserCredential.insert({"flag":false}) WriteResult({ "nInserted" : 1 })

Method - delete()

MongoDB's remove() method is used to remove document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
  1. Deletion Criteria : (Optional) deletion criteria according to documents will be removed.
  2. justOne : (Optional) if set to true or 1, then remove only one document.

Syntax:

Basic syntax of remove() method is as follows
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)


Save Vs Update

MongoDB's update() and save() methods are used to update document into a collection. The update() method update values in the existing document while the save() method replaces the existing document with the document passed in save() method.

MongoDB - Update()

The update() method updates values in the existing document.

Syntax:

Basic syntax of update() method is as follows
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)
By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.

MongoDB - Save()

The save() method replaces the existing document with the new document passed in save() method

Syntax

Basic syntax of mongodb save() method is shown below:
>db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})



How to avoid Duplicate Entry

To avoid duplicate entries in mongodb, Use an index with the {unique:true} option.
MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.


 For Example - 
db.homeCollections.ensureIndex({name:1},{unique:true});


If you wish for null values to be ignored from the unique key, then you have to also make the index sparse, by also adding the sparse option:

For Example - 

db.users.ensureIndex({email:1},{unique:true, sparse:true});

MongoDB - Create/Drop Database

The use Command

MongoDB use DATABASE_NAME is used to create database. The command will create a new database, if it doesn't exist otherwise it will return the existing database.

Syntax:
Basic syntax of use DATABASE statement is as follows:
use DATABASE_NAME
 
 
Example
>use krishnamongodb
switched to db krishnamongodb
 
 
To check your currently selected database use the command db
>db krishnamongodb
If you want to check your databases list, then use the command show dbs.
>show dbs 
local 0.78125GB 
test 0.23012GB

Your created database (krishnamongodb) is not present in list. To display database you need to insert atleast one document into it. To insert the document you need to create Collection first.

The dropDatabase() Method

MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax:

Basic syntax of dropDatabase() command is as follows:
 
db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will delete default 'test' database

Example:

First, check the list available databases by using the command show dbs
>show dbs
local                0.78125GB
krishnamongodb       0.23012GB
test                 0.23012GB
>
 
If you want to delete new database <krishnamongodb>, then dropDatabase() command would be as follows:

>use krishnamongodb
switched to db krishnamongodb
>db.dropDatabase()
>{ "dropped" : "krishnamongodb", "ok" : 1 }
>
 
Now check list of databases
>show dbs
local      0.78125GB
test       0.23012GB
>



MongoDB - Advantages

In MongoDB there is no concept of relationship. A relational database has a typical schema design that shows number of tables and the relationship between these tables.

Why should use MongoDB
  • Document Oriented Storage : Data is stored in the form of JSON style documents
  • Index on any attribute
  • Replication & High Availability
  • Auto-Sharding
  • Rich Queries
  • Fast In-Place Updates
  • Professional Support By MongoDB
Where should use MongoDB?
  • Big Data
  • Data Hub
Windows Installation steps - Follow below link
                                                  Latest Mongodb Installer 


Advantages of MongoDB over RDBMS
  • Uses internal memory for storing the (windowed) working set, enabling faster access of data  
  • No Schema : It is document database in which one collection holds different different 
  • documents. Number of fields, content and size of the document can be differ from one document to another.
  • Structure of a single object is clear
  • No complex joins
  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL
  • Ease of scale-out: MongoDB is easy to scale
    Conversion / mapping of application objects to database objects not needed 

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

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...