Tuesday 18 February 2014

JavaScript Quick Guide

What is JavaScript ?

JavaScript is:
  • JavaScript is a lightweight, interpreted programming language
  • Designed for creating network-centric applications
  • Complementary to and integrated with Java
  • Complementary to and integrated with HTML
  • Open and cross-platform

JavaScript Syntax:

A JavaScript consists of JavaScript statements that are placed within the <script>... </script> HTML tags in a web page.
You can place the <script> tag containing your JavaScript anywhere within you web page but it is preferred way to keep it within the <head> tags.
The <script> tag alert the browser program to begin interpreting all the text between these tags as a script. So simple syntax of your JavaScript will be as follows
<script ...>
  JavaScript code
</script>
The script tag takes two important attributes:
  • language: This attribute specifies what scripting language you are using. Typically, its value will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out the use of this attribute.
  • type: This attribute is what is now recommended to indicate the scripting language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like:
<script language="javascript" type="text/javascript">
  JavaScript code
</script>

Your First JavaScript Script:

Let us write our class example to print out "Hello World".
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
   document.write("Hello World!")
//-->
</script>
</body>
</html>
Above code will display following result:
Hello World!

Whitespace and Line Breaks:

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
Because you can use spaces, tabs, and newlines freely in your program so you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional:

Simple statements in JavaScript are generally followed by a semicolon character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if your statements are each placed on a separate line. For example, the following code could be written without semicolons
<script language="javascript" type="text/javascript">
<!--
  var1 = 10
  var2 = 20
//-->
</script>
But when formatted in a single line as follows, the semicolons are required:
<script language="javascript" type="text/javascript">
<!--
  var1 = 10; var2 = 20;
//-->
</script>
Note: It is a good programming practice to use semicolons.

Case Sensitivity:

JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.
So identifiers TimeTIme and TIME will have different meanings in JavaScript.
NOTE: Care should be taken while writing your variable and function names in JavaScript.

Comments in JavaScript:

JavaScript supports both C-style and C++-style comments, Thus:
  • Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
  • Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
  • JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.
  • The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.

JavaScript Placement in HTML File:

There is a flexibility given to include JavaScript code anywhere in an HTML document. But there are following most preferred ways to include JavaScript in your HTML file.
  • Script in <head>...</head> section.
  • Script in <body>...</body> section.
  • Script in <body>...</body> and <head>...</head> sections.
  • Script in and external file and then include in <head>...</head> section.

JavaScript DataTypes:

JavaScript allows you to work with three primitive data types:
  • Numbers eg. 123, 120.50 etc.
  • Strings of text e.g. "This text string" etc.
  • Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value.

JavaScript Variables:

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows:
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

JavaScript Variable Scope:

The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes.
  • Global Variables: A global variable has global scope which means it is defined everywhere in your JavaScript code.
  • Local Variables: A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

JavaScript Variable Names:

While naming your variables in JavaScript keep following rules in mind.
  • You should not use any of the JavaScript reserved keyword as variable name. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid.
  • JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. For example, 123test is an invalid variable name but_123test is a valid one.
  • JavaScript variable names are case sensitive. For example, Name and name are two different variables.

JavaScript Reserved Words:

The following are reserved words in JavaScript. They cannot be used as JavaScript variables, functions, methods, loop labels, or any object names.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

The Arithmatic Operators:

There are following arithmatic operators supported by JavaScript language:
Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
+Adds two operandsA + B will give 30
-Subtracts second operand from the firstA - B will give -10
*Multiply both operandsA * B will give 200
/Divide numerator by denumeratorB / A will give 2
%Modulus Operator and remainder of after an integer divisionB % A will give 0
++Increment operator, increases integer value by oneA++ will give 11
--Decrement operator, decreases integer value by oneA-- will give 9

The Comparison Operators:

There are following comparison operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
==Checks if the value of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

The Logical Operators:

There are following logical operators supported by JavaScript language
Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non zero then then condition becomes true.(A && B) is true.
||Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is false.

The Bitwise Operators:

There are following bitwise operators supported by JavaScript language
Assume variable A holds 2 and variable B holds 3 then:
OperatorDescriptionExample
&Called Bitwise AND operator. It performs a Boolean AND operation on each bit of its integer arguments.(A & B) is 2 .
|Called Bitwise OR Operator. It performs a Boolean OR operation on each bit of its integer arguments.(A | B) is 3.
^Called Bitwise XOR Operator. It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both.(A ^ B) is 1.
~Called Bitwise NOT Operator. It is a is a unary operator and operates by reversing all bits in the operand.(~B) is -4 .
<<Called Bitwise Shift Left Operator. It moves all bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying by 2, shifting two positions is equivalent to multiplying by 4, etc.(A << 1) is 4.
>>Called Bitwise Shift Right with Sign Operator. It moves all bits in its first operand to the right by the number of places specified in the second operand. The bits filled in on the left depend on the sign bit of the original operand, in order to preserve the sign of the result. If the first operand is positive, the result has zeros placed in the high bits; if the first operand is negative, the result has ones placed in the high bits. Shifting a value right one place is equivalent to dividing by 2 (discarding the remainder), shifting right two places is equivalent to integer division by 4, and so on.(A >> 1) is 1.
>>>Called Bitwise Shift Right with Zero Operator. This operator is just like the >> operator, except that the bits shifted in on the left are always zero,(A >>> 1) is 1.

The Assignment Operators:

There are following assignment operators supported by JavaScript language:
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assigne value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A

Miscellaneous Operator

The Conditional Operator (? :)

There is an oprator called conditional operator. This first evaluates an expression for a true or false value and then execute one of the two given statements depending upon the result of the evaluation. The conditioanl operator has this syntax:
OperatorDescriptionExample
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

The typeof Operator

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or boolean value and returns true or false based on the evaluation.

if statement:

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}

if...else statement:

The if...else statement is the next form of control statement that allows JavaScript to execute statements in more controlled way.

Syntax:

if (expression){
   Statement(s) to be executed if expression is true
}else{
   Statement(s) to be executed if expression is false
}

if...else if... statement:

The if...else if... statement is the one level advance form of control statement that allows JavaScript to make correct decision out of several conditions.

Syntax:

if (expression 1){
   Statement(s) to be executed if expression 1 is true
}else if (expression 2){
   Statement(s) to be executed if expression 2 is true
}else if (expression 3){
   Statement(s) to be executed if expression 3 is true
}else{
   Statement(s) to be executed if no expression is true
}

switch statement:

The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, adefault condition will be used.
switch (expression)
{
  case condition 1: statement(s)
                    break;
  case condition 2: statement(s)
                    break;
   ...
  case condition n: statement(s)
                    break;
  default: statement(s)
}

The while Loop

The most basic loop in JavaScript is the while loop which would be discussed in this tutorial.

Syntax:

while (expression){
   Statement(s) to be executed if expression is true
}

The do...while Loop:

The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.

Syntax:

do{
   Statement(s) to be executed;
} while (expression);

The for Loop

The for loop is the most compact form of looping and includes the following three important parts:
  • The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
  • The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
  • The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by a semicolon.

Syntax:

for (initialization; test condition; iteration statement){
     Statement(s) to be executed if test condition is true
}

The for...in Loop

for (variablename in object){
  statement or block to execute
}
In each iteration one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.

The break Statement:

The break statement, which was briefly introduced with the switch statement, is used to exit a loop early, breaking out of the enclosing curly braces.

The continue Statement:

The continue statement tells the interpreter to immediately start the next iteration of the loop and skip remaining code block.
When a continue statement is encountered, program flow will move to the loop check expression immediately and if condition remain true then it start next iteration otherwise control comes out of the loop.

Function Definition:

Before we use a function we need to define that function. The most common way to define a function in JavaScript is by using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. The basic syntax is shown here:
<script type="text/javascript">
<!--
function functionname(parameter-list)
{
  statements
}
//-->
</script>

Calling a Function:

To invoke a function somewhere later in the script, you would simple need to write the name of that function as follows:
<script type="text/javascript">

<!--
sayHello();
//-->
</script>

Exceptions

Exceptions can be handled with the common try/catch/finally block structure.
<script type="text/javascript">
<!--
try {
   statementsToTry
} catch ( e ) {
      catchStatements
} finally {
      finallyStatements
}
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of both). When an exception occurs in the catch block, the exception is placed in e and the catch block is executed. The finally block executes unconditionally after try/catch.

Alert Dialog Box:

An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:
<head>
<script type="text/javascript">
<!--
   alert("Warning Message");
//-->

</script>
</head>

Confirmation Dialog Box:

A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.
You can use confirmation dialog box as follows:
<head>
<script type="text/javascript">
<!--
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
   return true;
   }else{
      alert("User does not want to continue!");
   return false;
   }
//-->
</script>
</head>

Prompt Dialog Box:

You can use prompt dialog box as follows:
<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>

Page Re-direction

This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows:
<head>
<script type="text/javascript">
<!--
   window.location="http://www.newlocation.com";
//-->
</script>
</head>

The void Keyword:

The void is an important keyword in JavaScript which can be used as a unary operator that appears before its single operand, which may be of any type.
This operator specifies an expression to be evaluated without returning a value. Its syntax could be one of the following:
<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()

or:

void(func())
javascript:void(func())
//-->
</script>
</head>

The Page Printing:

JavaScript helps you to implement this functionality using print function of window object.
The JavaScript print function window.print() will print the current web page when executed. You can call this function directly using onclick event as follows:
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onclick="window.print()" />
</form>
</body>

Storing Cookies:

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this:

Syntax:

document.cookie = "key1=value1;key2=value2;expires=date";

Reading Cookies:

Reading a cookie is just as simple as writing one, because the value of the document.cookieobject is the cookie. So you can use this string whenever you want to access the cookie.
The document.cookie string will keep a list of name=value pairs separated by semicolons, wherename is the name of a cookie and value is its string value.

HTML Quick Reference Guide

This page is having a quick review of all the HTML tags discussed in this tutorial. If you need to know in detail about any tag then refer to HTML Tag List chapter.

HTML Basic Syntax:

  • HTML Element names and attribute names are not case sensitive.
  • HTML Documents start with a <!doctype...> statement, followed by a header and a text body all enclosed in <html>...</html>.
  • HTML Header is enclosed in <head>....</head> tags.
  • HTML Body is enclosed in <body>....</body> tags.
  • HTML Comments are written as <!-- A comment -->.

HTML Basic Document:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 4.0//EN">
<html>
<head>
<title>Document Title like HTML Tutorial</title>
</head>

<body>
   Document Text with other tags will come here.
</body>

</html>

Header elements:

  • <head> - Opening tag for the head of the document. The following optional tags can be placed inside the head.
  • <title>...</title> -Document title (not part of the text), recommended maximum length 64 characters.
  • <link ...> - Relationships for the document as a whole: common attributes are rel, rev, href.
  • <base href="url"> - Specifies the base URL of the document. This is used when dereferencing relative URLs in the page.
  • <base href="url" target="..."> - Specifies the base URL of the document. This is used when dereferencing relative URLs in the page. Also specifies the base target frame that all links will default to.
  • <meta ...> - Embed meta-information as if given by the server: attributes http-equiv, name, content.
    <meta http-equiv="refresh" content="N" > - Same page will be reloaded automatically after N seconds.
    <meta http-equiv="refresh" content="N" url="http://www.example.com> - Same other page will refresh automatically after N seconds.
    <meta http-equiv="expires" content="Wed, 08 Aug 2007 01:21:00 GMT" > - Specifies an expiration date for the page so that it will be reloaded after a certain date.
    <meta http-equiv="keywords" content="keyword1, keyword2,..." > - Specifies various keywords available on the page and to be used by the search engine.
    <meta http-equiv="description" content="A short description of the site" > - Specifies small description of the page and to be used by the search engine.
  • <style type="text/css" href="URL" /> - Specifies a CSS file to be used for the web page.
  • <script type="text/scripttype" href="URL" /> - Specifies a Javascript of VBscript file to be used for the web page.
  • <noscript> ... </noscript> - Encloses anything you want displayed by browsers that do not support inline scripts. This goes inside the <script> tags.
  • </head> - Closing tag for the head of the document.

Body Elements:

  • <body>...</body> - Encloses the main body of the document.
  • <hn>...</hn> - Makes the enclosed text a heading of various sizes where n is any number ranging from 1 to 6, and 1 creates the biggest heading while 6 creates the smallest.
  • <basefont size="n"> - Sets the default font properties for the entire page.
  • <isindex attributes> - Displays a text box indicating the presence of a searchable index. Simply adding this tag will not create a searchable page. The server must be set up to support it.
  • <img src="URL" attributes> - Places an inline image into the document.
  • <map attributes>...</map> - Specifies a collection of hot spots that define a client-side image map. The <area> tag can be used inside to define the hot spots.
  • <area attributes>...</area> - Specifies the shape and size of a hot spot to be used in the definition of a client-side image map. Used inside the <map> tag.
  • <marquee attributes>...</marquee> - Places a scrolling text marquee into the document.
  • <applet attributes>...</applet> - Inserts a Java applet in the HTML document. Any text placed between the opening and closing <applet> tags will be displayed by browsers that do not support JAVA.
  • <embed attributes>...</embed> - Inserts an embedded multimedia object, such as a sound file or video, into the page.
  • <a href="...">...</a> - When used with the HREF attribute, the enclosed text and/or graphic becomes a link to another document or anchor. When used with the NAME attribute, the enclosed text and/or graphic becomes an anchor.
  • <ol attributes>...</ol> - Puts the enclosed items marked with <li>, in a numbered list.
  • <ul attributes>...</ul> - Puts the enclosed items marked with <li>, in a bulleted list.
  • <dl>...</dl> - Creates a definition list. Within this container, <dt> specifies a definition term and <dd> specifies the definition.

Frame Elements:

  • <frameset attributes>...</frameset> - Defines a set of frames that will make up the page. The <frame>, and <noframes> tags go inside this. The <frameset> tag is used instead of the <body> tag. You can, however, include a <body> tag inside the <noframes> tags for browsers that do not support frames.
  • <frame attributes /> - Defines a single frame within a frameset.
  • <iframe attributes>...</iframe> - Defines a floating frame. Does not need to be placed within a frameset.
  • <noframes>...</noframes> - Placed inside the <frameset>, anything between the beginning and ending of this tag is viewable only by browsers that do not support frames. This tag is used to create pages that are compatible with older browsers that do not support frames.

Table Elements:

  • <table attributes>...</table> -Creates a table that can include any number of rows.
  • <caption attributes>...</caption> -Specifies the caption of the table.
  • <tr attributes>...</tr> - Specifies a table row. It can enclose the table heading and table data.
  • <th attributes>...</th> - Specifies a table heading.
  • <td attributes>...</td> - Specifies a table data cell.
  • <colgroup attributes /> - Specifies the properties of one or more columns. This tag generally goes right after the opening <table> tag.
  • <col attributes /> - Used with the <colgroup> tag, this specifies the properties of one column. This tag overrides any attributes specified in the <colgroup> tag that comes right before it.
  • <tbody>...</tbody> - Encloses the body of your table. This tag is optional unless you are using the <thead> or <tfoot> tags. It used to separate the rows in the table from those in the header or footer.
  • <tfoot>...</tfoot> - Encloses the table rows that are to be used as a footer. It is an optional tag and comes right after the ending <tbody> element.
  • <thead>...</thead> - Encloses the table rows that are to be used as a header. It is an optional tag and comes before the opening <tbody> element.

Form Elements:

  • <from attributes>...</from> - Specifies a form. Forms can be used to send user input to the server in the form of NAME/VALUE pairs.
  • <input attributes /> - Specifies a control or input area for a form, from which a NAME/VALUE pair will be returned to the server. It could be Checkbox, Raidobox, password, text, reset, submit, hidden and image.
  • <select attributes>...</select> - Creates a drop-down list of items. The list items are defined by the <option> tags placed inside the opening and closing <select> tag.
  • <option value="..." /> - Specifies an item in the drop down list. Placed within the opening and closing <select> tags. Any text following the <option> tag is what the user will see in the list.
  • <textarea attributes>...</textarea> - Creates a multi-lined text entry box. Any text placed in between the tags is used as the default text string that is displayed when the page is loaded.
  • <button attributes>...</button> - allows you to have push buttons on forms that more closely resemble push buttons available in Windows and other applications.

Text Formatting Elements:

  • <address>.....< /address> - Encloses the signature file of the author of the page. Text is displayed in italics.
  • <acronym>.....< /acronym> - indicates an acronym in the text.
  • <b>...< /b> - Boldfaces the enclosed text.
  • <big>...< /big> - Makes the enclosed text one size larger.
  • <blink>.....< /blink> - Makes the enclosed text blink continually.
  • <blockquote>.....< /blockquote> - Encloses a long quote. Both the left and right margins are indented.
  • <br> - Inserts a line break.
  • <center>.....< /center> - Centers the enclosed elements.
  • <cite>.....< /cite> - Encloses a citation such as the title of a book or paper.
  • <code>.....< /code> - Encloses a sample of code. The text is rendered in small font.
  • <comment>.....< /comment> - Encloses a comment. Text inside the tags is ignored unless it contains HTML code.
  • <del>.....< /del> - To mark the document text that has been deleted since a previous version.
  • <dfn>.....< /dfn> - Encloses a definition. Text inside the tags is formatted to look like a definition.
  • <div>...< /div> - Specifies the alignment of the enclosed elements. Can be used to divide a document into sections that are aligned differently.
  • <em>...< /em> - Emphasis on the enclosed text (Italics).
  • <font attributes>...< /font> - Sets the font properties for the enclosed text.
  • <fieldset attributes>...< /fieldset> - Allows you can group related form fields, making your form easier to read and use.
  • <hr attributes /> - Inserts a horizontal line.
  • <i>...< /i> - The enclosed text is italics.
  • <ins>...< /ins> - To mark parts of a document that have been added since the document's last version.
  • <label>...< /label> - Allows you to lable a tag.
  • <kbd>...< /kbd> - Specifies text to be entered at the keyboard. Text is rendered as bold and fixed-width.
  • <p attributes>...< /p> - Designates the enclosed text as a plain paragraph.
  • <q>...</q> - acts much the same as the <blockquote> tag, but applies to shorter quoted sections, ones that don't need paragraph breaks.
  • <pre>.....< /pre> - Displays text in fixed-width type without collapsing spaces.
  • <s>.....< /s> - Displays text with a line through it. The <strike> tag does exactly the same.
  • <samp>...< /samp> - Indicates sample output from a form or program. Text is rendered in small font.
  • <small>...< /small> - Makes the enclosed text one size smaller.
  • <spacer attributes>...< /spacer> - Inserts blocks of spaces into HTML documents.
  • <strong>...< /strong> - Stronger emphasis on the enclosed text.
  • <sub>...< /sub> - Renders the enclosed text in subscript.
  • <sup>...< /sup> - Renders the enclosed text in superscript.
  • <tt>...< /tt> - The enclosed text is typewriter font.
  • <u>...< /u> - The enclosed text in underlined.
  • <var>...< /var> - Specifies a variable. Text is rendered in small fixed-width type.
  • <wbr> - Causes text enclosed by the NOBR tags to wrap only if necessary.

MongoDB Quick Guide

MongoDB Overview

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document.

Database

Database is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases.

Collection

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data.

Sample document

Below given example shows the document structure of a blog site which is simply a comma separated key value pair.
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100, 
   comments: [ 
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2011,1,20,2,15),
         like: 0 
      },
      {
         user:'user2',
         message: 'My second comments',
         dateCreated: new Date(2011,1,25,7,45),
         like: 5
      }
   ]
}

Install MongoDB On Windows

To install the MongoDB on windows, first doownload the latest release of MongoDB fromhttp://www.mongodb.org/downloads
Now extract your downloaded file to c:\ drive or any other location. Make sure name of the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version]. Here [version] is the version of MongoDB download.
Now open command prompt and run the following command
C:\>move mongodb-win64-* mongodb
      1 dir(s) moved.
C:\>
In case you have extracted the mondodb at different location, then go to that path by using command cd FOOLDER/DIR and now run the above given process.
MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute the following command sequence
C:\>md data
C:\md data\db
If you have install the MongoDB at different location, then you need to specify any alternate path for\data\db by setting the path dbpath in mongod.exe. For the same issue following commands
In command prompt navigate to the bin directory present into the mongodb installation folder. Suppose my installation folder is D:\set up\mongodb
 
C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
This will show waiting for connections message on the console output indicates that the mongod.exe process is running successfully.
Now to run the mongodb you need to open another command prompt and issue the following command
 
D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
This will show that mongodb is installed and run successfully. Next time when you run mongodb you need to issue only commands
 
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe

Create Database

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:

If you want to create a database with name <mydb>, then use DATABASE statement would be as follows:
>use mydb
switched to db mydb
To check your currently selected database use the command db
>db
mydb
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 (mydb) is not present in list. To display database you need to insert atleast one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local      0.78125GB
mydb       0.23012GB
test       0.23012GB
In mongodb default database is test. If you didn't create any database then collections will be stored in test database.

Drop Database

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:

If you want to delete new database <mydb>, then dropDatabase() command would be as follows:
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>

Create Collection

MongoDB db.createCollection(name, options) is used to create collection. In the command, name is name of collection to be created. Options is a document and used to specify configuration of collection
ParameterTypeDescription
NameStringName of the collection to be created
OptionsDocument(Optional) Specify options about memory size and indexing
Options parameter is optional, so you need to specify only name of the collection.

Syntax:

Basic syntax of createCollection() method is as follows
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections
>show collections
mycollection
system.indexes

List of options

FieldTypeDescription
cappedBoolean(Optional) If true, enables a capped collection. Capped collection is a collection fixed size collecction that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.
autoIndexIDBoolean(Optional) If true, automatically create index on _id field.s Default value is false.
sizenumber(Optional) Specifies a maximum size in bytes for a capped collection. If If capped is true, then you need to specify this field also.
maxnumber(Optional) Specifies the maximum number of documents allowed in the capped collection.
While inserting the document, MongoDB first checks size field of capped collection, then it checks max field.

Syntax :

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }
>
In mongodb you don't need to create collection. MongoDB creates collection automatically, when you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

Drop Collection

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()

Example:

Below given example will drop the collection with the name mycollection
>use mydb
switched to db mydb
>db.mycollection.drop()
true
>

Insert Document

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

Syntax

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

Example

>db.mycol.insert({
   _id: ObjectId(7df78ad8902c),
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
})
Here mycol 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.

Example

>db.post.insert([
{
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   title: 'NoSQL Database', 
   description: 'NoSQL database doesn't have tables',
   by: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 20, 
   comments: [ 
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2013,11,10,2,35),
         like: 0 
      }
   ]
}
])

Query Document

To query data from MongoDB collection, you need to use MongoDB's find() method.

Syntax

Basic syntax of find() method is as follows
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non structured way. To display the results in a formatted way, you can use pretty() method.

Syntax:

>db.mycol.find().pretty()

Example

>db.mycol.find().pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>
Apart from find() method there is findOne() method, that reruns only one document.

RDBMS Where Clause Equivalents in MongoDB

To query the document on the basis of some condition, you can use following operations
OperationSyntaxExampleRDBMS Equivalent
Equality{<key>:<value>}db.mycol.find({"by":"tutorials point"}).pretty()where by = 'tutorials point'
Less Than{<key>:{$lt:<value>}}db.mycol.find({"likes":{$lt:50}}).pretty()where likes < 50
Less Than Equals{<key>:{$lte:<value>}}db.mycol.find({"likes":{$lte:50}}).pretty()where likes <= 50
Greater Than{<key>:{$gt:<value>}}db.mycol.find({"likes":{$gt:50}}).pretty()where likes > 50
Greater Than Equals{<key>:{$gte:<value>}}db.mycol.find({"likes":{$gte:50}}).pretty()where likes >= 50
Not Equals{<key>:{$ne:<value>}}db.mycol.find({"likes":{$ne:50}}).pretty()where likes != 50

AND in MongoDB

Syntax:

In the find() method if you pass multiple keys by separating them by ',' then MongoDB treats it ANDcondition. Basic syntax of AND is shown below:
>db.mycol.find({key1:value1, key2:value2}).pretty()

Example

Below given example will show all the tutorials written by 'tutorials point' and whose title is 'MongoDB Overview'
>db.mycol.find({"by":"tutorials point","title": "MongoDB Overview"}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>
For the above given example equivalent where clause will be ' where by='tutorials point' AND title='MongoDB Overview' '. You can pass any number of key, value pairs in find clause.

OR in MongoDB

Syntax:

To query documents based on the OR condition, you need to use $or keyword. Basic syntax of OR is shown below:
>db.mycol.find(
   {
      $or: [
      {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Example

Below given example will show all the tutorials written by 'tutorials point' or whose title is 'MongoDB Overview'
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Using AND and OR together

Example

Below given example will show the documents that have likes greater than 100 and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent sql where clause is 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
>db.mycol.find("likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}] }).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

Update Document

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

MongoDB Update() method

Syntax:

Basic syntax of update() method is as follows
>db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

Example

Consider the mycol collectioin has following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will set the new title 'New MongoDB Tutorial' of the documents whose title is 'MongoDB Overview'
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>
By default mongodb will update only single document, to update multiple you need to set a paramter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})

MongoDB Save() Method

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})

Example

Following example will replace the document with the _id '5983548781331adf45ec7'
>db.mycol.save(
   {
      "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point New Topic", "by":"Tutorials Point"
   }
)
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic", "by":"Tutorials Point"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>

Delete Document

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)

Example

Consider the mycol collectioin has following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB Overview'
>db.mycol.remove({'title':'MongoDB Overview'})
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>

Remove only one

If there are multiple records and you want to delete only first record, then set justOne parameter inremove() method
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All documents

If you don't specify deletion criteria, then mongodb will delete whole documents from the collection.This is equivalent of SQL's truncate command.
>db.mycol.remove()
>db.mycol.find()
>

MongoDB Projection

In mongodb projection meaning is selecting only necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them.
MongoDB's find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB when you execute find() method, then it displays all fields of a document. To limit this you need to set list of fields with value 1 or 0. 1 is used to show the filed while 0 is used to hide the field.

Syntax:

Basic syntax of find() method with projection is as follows
>db.COLLECTION_NAME.find({},{KEY:1})

Example

Consider the collection myycol has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display the title of the document while quering the document.
>db.mycol.find({},{"title":1,_id:0})
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
{"title":"Tutorials Point Overview"}
>
Please note _id field is always displayed while executing find() method, if you don't want this field, then you need to set it as 0

Limit Documents

MongoDB Limit() Method

To limit the records in MongoDB, you need to use limit() method. limit() method accepts one number type argument, which is number of documents that you want to displayed.

Syntax:

Basic syntax of limit() method is as follows
>db.COLLECTION_NAME.find().limit(NUMBER)

Example

Consider the collection myycol has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display only 2 documents while quering the document.
>db.mycol.find({},{"title":1,_id:0}).limit(2)
{"title":"MongoDB Overview"}
{"title":"NoSQL Overview"}
>
If you don't specify number argument in limit() method then it will display all documents from the collection.

MongoDB Skip() Method

Apart from limit() method there is one more method skip() which also accepts number type argument and used to skip number of documents.

Syntax:

Basic syntax of skip() method is as follows
>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

Example:

Following example will only display only second document.
>db.mycol.find({},{"title":1,_id:0}).limit(1).skip(1)
{"title":"NoSQL Overview"}
>
Please note default value in skip() method is 0

Sorting Documents

To sort documents in MongoDB, you need to use sort() method. sort() method accepts a document containing list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Syntax:

Basic syntax of sort() method is as follows
>db.COLLECTION_NAME.find().sort({KEY:1})

Example

Consider the collection myycol has the following data
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display the documents sorted by title in descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Please note if you don't specify the sorting preference, then sort() method will display documents in ascending order.

MongoDB Indexing

Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require the mongod to process a large volume of data.
Indexes are special data structures, that store a small portion of the 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 as specified in index.
To create an index you need to use ensureIndex() method of mongodb.

Syntax:

Basic syntax of ensureIndex() method is as follows()
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of filed on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1.

Example

>db.mycol.ensureIndex({"title":1})
>
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
>
ensureIndex() method also accepts list of options (which are optional), whose list is given below:
ParameterTypeDescription
backgroundBooleanBuilds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
uniqueBooleanCreates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
namestringThe name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
dropDupsBooleanCreates a unique index on a field that may have duplicates. MongoDB indexes only the first occurrence of a key and removes all documents from the collection that contain subsequent occurrences of that key. Specify true to create unique index. The default value is false.
sparseBooleanIf true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false.
expireAfterSecondsintegerSpecifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.
vindex versionThe index version number. The default index version depends on the version of mongod running when creating the index.
weightsdocumentThe weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score.
default_languagestringFor a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value isenglish.
language_overridestringFor a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language.

MongoDB Aggregation

Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In sql count(*) and with group by is an equivalent of mongodb aggregation. For the aggregation in mongodb you should use aggregate() method.

Syntax:

Basic syntax of aggregate() method is as follows
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

Example:

In the collection you have the following data:
{
   _id: ObjectId(7df78ad8902c)
   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   _id: ObjectId(7df78ad8902d)
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'tutorials point',
   url: 'http://www.tutorialspoint.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
},
{
   _id: ObjectId(7df78ad8902e)
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750
},
Now from the above collection if you want to display a list that how many tutorials are written by each user then you will use aggregate() method as shown below:
> db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{
   "result" : [
      {
         "_id" : "tutorials point",
         "num_tutorial" : 2
      },
      {
         "_id" : "tutorials point",
         "num_tutorial" : 1
      }
   ],
   "ok" : 1
}
>
Sql equivalent query for the above use case will be select by_user, count(*) from mycol group by by_user
In the above example we have grouped documents by field by_user and on each occurance of by_user previous value of sum is incremented. There is a list available aggregation expressions.
ExpressionDescriptionExample
$sumSums up the defined value from all documents in the collection.db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : "$likes"}}}])
$avgCalculates the average of all given values from all documents in the collection.db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$avg : "$likes"}}}])
$minGets the minimum of the corresponding values from all documents in the collection.db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$min : "$likes"}}}])
$maxGets the maximum of the corresponding values from all documents in the collection.db.mycol.aggregate([{$group : {_id : "$by_user", num_tutorial : {$max : "$likes"}}}])
$pushInserts the value to an array in the resulting document.db.mycol.aggregate([{$group : {_id : "$by_user", url : {$push: "$url"}}}])
$addToSetInserts the value to an array in the resulting document but does not create duplicates.db.mycol.aggregate([{$group : {_id : "$by_user", url : {$addToSet : "$url"}}}])
$firstGets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycol.aggregate([{$group : {_id : "$by_user", first_url : {$first : "$url"}}}])
$lastGets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage.db.mycol.aggregate([{$group : {_id : "$by_user", last_url : {$last : "$url"}}}])

MongoDB Replication

Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers, replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup.

Why Replication?

  • To keep your data safe
  • High (24*7) availability of data
  • Disaster Recovery
  • No downtime for maintenance (like backups, index rebuilds, compaction)
  • Read scaling (extra copies to read from)
  • Replica set is transparent to the application

How replication works in MongoDB

MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica one node is primary node that receives all write operations. All other instances, secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node.
  1. Replica set is a group of two or more nodes (generally minimum 3 nodes are required).
  2. In a replica set one node is primary node and remaining nodes are secondary.
  3. All data replicates from primary to secondary node.
  4. At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected.
  5. After the recovery of failed node, it again join the replica set and works as a secondary node.
A typical diagram of mongodb replication is shown in which client application always interact with primary node and primary node then replicate the data to the secondary nodes.
MongoDB Replication

Replica set features

  • A cluster of N nodess
  • Anyone node can be primary
  • All write operations goes to primary
  • Automatic failover
  • Automatic Recovery
  • Consensus election of primary

Set up a replica set

In this tutorial we will convert standalone mongod instance to a replica set. To convert to replica set follow the below given steps:
  • Shutdown already running mongodb server.
  • Now start the mongodb server by specifying --replSet option. Basic syntax of --replSet is given below:
    mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"

    Example

    mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0
    It will start a mongod instance with the name rs0, on port 27017
  • Now start the command prompt and connect to this mongod instance.
  • In mongo client issue the command rs.initiate() to initiate a new replica set.
  • To check the replica set configuration issue the command rs.conf().
  • To check the status of replica sete issue the command rs.status().

MongoDB Create Backup

Dump MongoDB Data

To create backup of database in mongodb you should use mongodump command. This command will dump all data of your server into dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server.

Syntax:

Basic syntax of mongodump command is as follows
>mongodump

Example

Start your mongod server. Assuming that your mongod server is running on localhost and port 27017. Now open a command prompt and go to bin directory of your mongodb instance and type the command mongodump
Consider the mycol collectioin has following data.
>mongodump
The command will connect to the server running at 127.0.0.1 and port 27017 and back all data of the server to directory /bin/dump/. Output of the command is shown below:DB Stats
There are a list of available options that can be used with the mongodump command.
This command will backup only specified database at specified path
SyntaxDescriptionExample
mongodump --host HOST_NAME --port PORT_NUMBERThis commmand will backup all databases of specified mongod instance.mongodump --host tutorialspoint.com --port 27017
mongodump --dbpath DB_PATH --out BACKUP_DIRECTORYmongodump --dbpath /data/db/ --out /data/backup/
mongodump --collection COLLECTION --db DB_NAMEThis command will backup only specified collection of specified database.mongodump --collection mycol --db test

Restore data

To restore backup data mongodb's mongorestore command is used. This command restore all of the data from the back up directory.

Syntax

Basic syntax of <mongorestore command is
>mongorestore
Output of the command is shown below:DB Stats