MEAN STACK

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

In the previous chapter of JavaScript, we have learned the method to target the HTML Element. Now we are about to move on 'How many possible ways are there to display output in JavaScript?'

Although JavaScript executes many of task that has no concern with the display but most of the times different types of JavaScript output data required to display on browser.

JavaScript can display output data in different ways. Below are the properties, methods, and functions that can be used to display output data in JavaScript.

  1. Using innerHTML property
  2. Using innerText property
  3. Using textContent property
  4. Using document.write() method
  5. Using alert()
  6. Using console.log()
  7. Using print()

Using innerHTML property

The innerHTML property is part of the Document Object Model (DOM) that allows JavaScript code to manipulate a website being displayed. Specially it allows reading and replacing everything within a DOM Element (HTML tag).

The innerHTML property can output the data in the form of HTML content. You check in the example.


Code Copied
<script>
    document.write(document.getElementById("test").innerHTML);
</script>
Try Yourself

Using innerText property

The innerText property sets or returns the text content of the specified node and all its descendants.

If innerText property is used then child nodes are removed and replaced by a single text node.


Code Copied
<script>
    document.write(document.getElementById("text").innerText);
</script>
Try Yourself

Using textContent property

The textContent property us similar to the innerText property of JavaScript but there is a difference between them. We will discuss those differences later in this article.


Code Copied
<script>
    document.write(document.getElementById("text").textContent);
</script>
Try Yourself

Using document.write() method

The document.write() is a method which writes a string of text to document stream. The write() method writes HTML expression or JavaScript code to a document. The write() method is used for testing purposes mostly.

If document.write() method is used after fully loaded HTML page then it will override all the existing HTML and gives new HTML Page.


Code Copied
<script>
    document.write(document.getElementById("text").textContent);
</script>
Try Yourself

Using alert()

The alert() method in JavaScript displays an alert box with a specified message along with an 'OK' button. It is often used to make sure that information comes through the user. The alert() box takes the focus away from the current window and forces the browser to read the message.


Code Copied
<script>
    function getAlert(){
        alert(document.getElementById("test").innerHTML);
    }     
</script>
Try Yourself

Using console.log()

The console.log() is a function in JavaScript that is used to print any kind of variables defined before console.log()or to just print any message that needs to be displayed to the user.

console.log() is used for debugging purposes we can call the console.log() method in the browser to display data.


Code Copied
<script>
    console.log(document.getElementById("test").innerHTML);        
</script>
Try Yourself

Using print()

JavaScript print method is used to print the contents of the current window. It basically opens a print dialog box in the browser.


Code Copied
<script>
    function getPrint(){
        print();
    }         
</script>
Try Yourself

What is the difference between innerHTML, innerText, and textContent?

innerHTML property allows us to work with rich text and doesn't automatically encode and decode text. We can get the data to display in a rich text format where CSS can also work.

innerText property retrieves and sets the content from the HTML tag as plain text where spaces are trimmed in results but the CSS styling can be displayed in results. 

textContent property retrieves and sets the content similarly innerText but spaces and whitespace cannot be trimmed and CSS styling cannot be displayed in results.

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

ID and Class attributes are the most common selectors that widely used to target the HTML DOM while working with JavaScript. Have you ever thought why we mostly prefer to use the id and class while many of the methods are available to target the HTML Elements in JavaScript?

First of all, we look at all the methods to target the HTML Elements using JavaScript.

For reference you can check the multiple examples below.

How to target HTML elements using ‘id’?



    <div id="test"></div>
    <script>
        //we want to print "Hello World inside div"
        document.getElementById("test").innerHTML="Hello World!";
    </script>
Try Yourself

In this method we target the Single HTML element within the DOM tree using its ID attribute. While using ID, it always returns a single node of HTML DOM.

The most important thing is that using two or more HTML elements with the same ID on the same web page can produce the unexpected error, therefore, we should be careful using the ID attribute while creating the web page.

How to target HTML Elements using ‘class’?



    <!--Different HTML tags with same classes-->
    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    
    <script>
        document.getElementsByClassName("test")[0].innerHTML="This Heading";
        document.getElementsByClassName("test")[1].innerHTML="This is div";
        document.getElementsByClassName("test")[2].innerHTML="This is paragraph";
        document.getElementsByClassName("test")[3].innerHTML="This is span";
    </script>
Try Yourself

In this method we target one or more HTML Elements with the same class name. When we target HTML Elements with the class name, each HTML element with the same class becomes the part of that class, it returns a list of nodes (referred to as NodeList in the console) instead of a single node where each node can be referred with the index number like given in above example.

The index number of each node is decided by its appearance on the web page. For e.g. the index of the very first node is referred to as [0] and second as [1] and so on. If the position of any node is changed on the webpage then its index will be also changed accordingly and it might affect the index of rest upcoming nodes also.

Even we target a single element with the class name, it returns a list of nodes but the difference is that there is only a single node present in that list.

Therefore it is a better idea to use class names but in a structured way.

We will study more about classes in further chapters

How to target HTML Elements using ‘tag name’?



    <h1 class="test"></h1>
    <div class="test"></div>
    <p class="test"></p>
    <span class="test"></span>
    <span class="test"></span>
    <script>
        document.getElementsByTagName("H1")[0].innerHTML="This Heading";
        document.getElementsByTagName("DIV")[0].innerHTML="This is div";
        document.getElementsByTagName("P")[0].innerHTML="This is paragraph";
        document.getElementsByTagName("SPAN")[0].innerHTML="This is first span";
        document.getElementsByTagName("SPAN")[1].innerHTML="This is second span";
    </script>
Try Yourself

In this method we target one or more HTML elements with their tag name. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

How to target HTML Elements using the ‘name’ attribute?



    <!--Different HTML tags with same classes-->
    <form action="">
        <div><input type="text" name="fname" placeholder="first name" value="John"/></div><br/>
        <div><input type="text" name="lname" placeholder="last name" value="Doe"/></div><br/>
        <div><input type="email" name="email" placeholder="email" value="john@progrramers.com"/></div><br/>
        <div><input type="url" name="website" placeholder="website" value="https://progrramers.com"/></div><br/>
        <div><input type="button" name="submit" value="Save" onclick="formdata()"/></div><br/>
    </form>
    <p name="test"></p>
    <script>
        function formdata(){
            var fname=document.getElementsByName('fname')[0].value;
            var lname=document.getElementsByName('lname')[0].value;
            var email=document.getElementsByName('email')[0].value;
            var website=document.getElementsByName('website')[0].value;
            document.getElementsByName("test")[0].innerHTML = "First name: "+fname+"<br/>Last name: "+lname+"<br/>Email: "+email+"<br/>Website: "+website;
        }
    </script>
Try Yourself

In this method we target one or more HTML elements with their name attribute. You can see in the above example. Likewise class case, it also returns a set the node list where each node can be accessed by the specific index number.

Note: Name attribute’s value also can be accessible in the post method of server-side scripts like PHP. We will deal with it during the tutorials of server-side scripts.

How to target HTML Elements using the ‘querySelector’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelector('#test_id').innerHTML="This is First DIV Element.";
        document.querySelector('.test_class').innerHTML="This is Second DIV Element.";
    </script>
Try Yourself

In this method we target single HTML Element using CSS selector. In CSS if we want to target element with tag name we use the tag name, or if we want to use the ID or Class then we use ‘#’ with ID and ‘.’ with the class name. Similarly we can use CSS all selector to with query selector method.

Likewise ID case, it returns only the first node present on the web page.

How to target HTML Elements using ‘querySelectorAll’ method?



    <div id="test_id"></div>
    <div class="test_class"></div>
    <div class="test_class"></div>
    
    <script>
        document.querySelectorAll('#test_id')[0].innerHTML="This is First DIV Element.";
        document.querySelectorAll('.test_class')[0].innerHTML="This is Second DIV Element.";
        document.querySelectorAll('.test_class')[1].innerHTML="This is Third DIV Element.";
    
        console.log(document.querySelectorAll("DIV"));
    </script>
Try Yourself

This method is the same as the query selector method but in this method we target one or more HTML Elements using CSS selector and it returns a set the node list where each node can be accessed by the specific index number.

You have seen all the examples given above. These are the methods to target the HTML DOM or HTML DOMs in JavaScript. You must know a few things also which are mentioned below

  1. The methods that return the list of nodes can be looped. Check example 7 ahead.
  2. Although node list can be looped they aren’t referred to as an array because array must have few methods like push, splice & sort but not in case of node list.
  3. ID, Class, and Name are the attributes that can be directly accessed in JavaScript. For reference Check example 8.
  4. Id & name attribute can have one value at a time and can be used only once on the webpage but the class can have multiple values at the same time. The value should be separated by space. For e.g. class=”container box primary”. There are three different classes in the example container, box & primary.

How to apply loop on a NodeList?


Code Copied
<div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <div class="test"></div>
    <script>
        var el=document.querySelectorAll('.test'),n=1;
        el.forEach(element => {
            element.innerHTML="This is DIV No. "+(n++);
        });
    </script>
Try Yourself

How to Find ID, Class & Name Attribute Values?


<div id="test_id">This DIV has id Attribute</div>
    <!--Class can have multiple value-->
    <div class="test_class1 test_class2 test_class3">This DIV has class Attribute</div>
    <div name="test_name">This DIV has name Attribute</div>


    <p id="result_1"></p>
    <p id="result_2"></p>
    <p id="result_3"></p>

    <script>
        document.getElementById("result_1").innerHTML = document.getElementById("test_id").id;
        document.getElementById("result_2").innerHTML = document.getElementsByClassName("test_class1")[0].className;
        document.getElementById("result_3").innerHTML = document.getElementsByName("test_name")[0].getAttribute("name");
    </script>
Try Yourself
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

In the previous chapter of JavaScript Tutorials, we have learned about what JavaScript can do? Now we are about to learn that How and Where to use JavaScript on an HTML Document?

How to use JavaScript on HTML Documents?

Before we go forward we need to understand the most important thing and that is ‘How a web page is parsed on a web browser? This question is most important because until unless we don’t understand the working principle of a webpage, we can’t develop it with any client-side scripting language like JavaScript.

We already know that JavaScript manipulates the HTML DOM by changing its inner HTML, inner Text, values, and style. JavaScript is used to perform a certain task or chain of the task and execute it on the browser by changing the status of HTML DOMs. To do so we have to find and target the specific HTML DOM with various methods that we will learn in upcoming chapters. 

To understand the above sentences we need to check the below example.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of JavaScript</title>
</head>
<body>
    <div id="test"></div>
    <script>
        document.getElementById("test").innerHTML = "Hello World!";
    </script>
</body>
</html>
        
Try Yourself

What we see in the example above given. There are two things in the above example

The first thing we see there is an HTML document contains a DIV element with an attribute named ID. The value of the ID is ‘test’. We required printing Hello World inside the DIV element dynamically using JavaScript when a web page is loaded.

Second thing, there is also a script tag just before the end of body tag where are some codes are written which is not likely HTML codes. Actually the codes written in script tags are JavaScript. JavaScript codes are written between <script> tags on HTML documents.

Now to understand the working principle of the above example you can copy and paste the above code in your favorite HTML editor and save the file with .html file extension and run into your favorite browser. You will see ‘Hello World’ printed on the web page.

On the web page loading process, we simply target the HTML DIV tag by its ID using “document.getElementById()” method and setting the value ‘Hello World’ of its ‘innerText’ so that when the web page completely falls on the browser it prints ‘Hello World’ text.

This is how we target the HTML DOM on an HTML web page using JavaScript. This was only an example but in professional projects, we do something like this on a large scale. We will sure study that in this tutorial series.

 

Why & when use type attribute within <script> tags?

Now we know that JavaScript codes are written inside <script> tags. Let’s check a few another example given below

JavaScript codes with a type attribute in script tags


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Use of Type Attribute</title>
</head>
<body>
    <div id="test"></div>
    <script type="text/javascript">
        document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
    </script>
</body>
</html>
        
Try Yourself

JavaScript codes without type attribute in script tags


<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Example of HTML5 Version Doctype</title>
</head>
<body>
     <div id="test"></div>
     <script>
          document.getElementById("test").innerHTML="JavaScript is a Scripting Language.";
     </script>
</body>
</html>
Try Yourself

In both examples can you see the difference? You can see in example 2 <script> tag is used with type attribute and in example no 3 <script> tag is used without type attribute.

This is happening because of the HTML Document version. Before HTML version 5 JavaScript is not the default scripting language of HTML so we must specify the type of scripting language. Older browsers are not able to find the type of script language therefore JavaScript might not work.

But since HTML 5th version JavaScript is becoming the default scripting language, therefore, we are not forced to use type attribute in script tag while working with JavaScript.

Note: Above both examples can work in the latest browsers without type attribute. The problem comes with only older browsers.

Where to use JavaScript on HTML Documents?

Above all the examples are demonstrating to us how to use JavaScript on an HTML Document. Now let’s move on Where to use JavaScript on HTML Documents?

Before we go ahead first we need to understand how an HTML Document is parsed on a browser and become a web page.  Usually, HTML Document is parsed on a browser top to bottom and left to right. It means that the most top line of the document is parsed first into left to right direction therefore whole HTML DOMs must be parsed over web browsers before JavaScript functions are called.

If it doesn’t happen then the browser console will throw the script error and it can be case wise different. Another thing is that by default JavaScript declared functions and variables are stored on the top level in primary memory while launching the web page whether they are declared on top of page or bottom of the page, therefore, we should not worry about where we are trying to keep our JavaScript codes on HTML document. Therefore we can place JavaScript declared functions and variable between the <head> tags like the below-mentioned example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Declared Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button onclick="myFunction()">Click</button>
</body>
</html>
        
Try Yourself

We should worry about only JavaScript calling functions which must be executed at the most end of part of the web page so that All HTML DOMs can found easily found which are targeted by JavaScript. It is good practice to place JavaScript codes on the most bottom part of HTML <body> tags, mention like below example


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Calling Functions</title>
    <script>
        //declared functions and variables
        var x = "You have clicked the button."
        function myFunction(){
            document.getElementById('test').innerHTML=x;
        }
    </script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>

    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        
Try Yourself

Also, it is observed that placing JavaScript code at the bottom of <body> tags improves the display speed because script interpretation slows down the display.

Above shown examples are a type of internal JavaScript but there is another type of JavaScript also which can improve the development speed without harming the performance of the web site.

What are the types of placement of JavaScript on an HTML Document?

  1. Internal JavaScript
  2. External JavaScript

What is Internal JavaScript?

Internal JavaScript is a practice in which all the JavaScript codes are written separately in every document. The drawback of this practice is that we have to write a similar type of code again and again which slows down the development speed. All the above show examples are a type of internal JavaScript.

What is External JavaScript?

In this practice JavaScript codes are written in a separate file which has the file extension “.js”. To embed the external JavaScript file on the web pages we have to use <script> tags with a specific attribute named ‘src’ which holds the location path of the external JavaScript file.

Take a look at a below-given example. This example is created using jQuery CDN. You will learn jQuery in further chapters.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of Absolute Path Over jQuery Content Delivery Network (CDN)</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        $(document).ready(function(){
            $('#test-button').click(function(){
            $('#test').html("Hello World!")
            });
        });
    </script>
</body>
</html>
        
Try Yourself

Few points must be noticed while creating an external JavaScript file.

  1. JavaScript file created with .js extension is not a web page rather a script page.
  2. JavaScript file cannot contain the <script> tags.
  3. Multiple JavaScript pages can be used on a single HTML document.
  4. It is important to declare the HTML web page doctype because before HTML5 JavaScript not default scripting language. We have to specify the ‘type’ attribute in <script> tags to make active scripting language.

What are the advantages of external JavaScript?

  1. HTML and JavaScript codes are separated while using external JavaScript
  2. JavaScript code which required to be executed again & again on different pages is not required to write multiple times.
  3. It makes developers easy to maintain and develop the program fast.
  4. You can use different specialist code editor at the same time. For example, Notepad++ is best for HTML, and VSCode is best suitable for JavaScript.
  5. External JavaScript code can be cached into the client device therefore cached JavaScript file can speed up the page load.

Using absolute and relative path reference for external JavaScript

 External JavaScript files can embed on HTML documents using relative or absolute path references which show below in the examples.

To understand relative or absolute file path learn HTML5 Tutorial - HTML File Path


//declared functions and variables
  var x = "You have clicked the button."
  function myFunction(){
  document.getElementById('test').innerHTML=x;
}
        


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example of External JS file using absolute path</title>
    <script src="script.js"></script>
</head>
<body>
    <div id="test"></div>
    <button id="test-button">Click</button>
    <script>
        //calling function defined in <head> tags
        document.getElementById("test-button").onclick=function(){
            myFunction();
        }
    </script>
</body>
</html>
        

Copy the JavaScript codes given in example 7 and paste into your favorite text editor and save as script.js and after that once again create a new file in the text editor and copy HTML codes from example 8 and paste into the text editor and save the document as 'example8.html'. Both the files must be located into same directory. 

After that run the example8.html file in the browser, you will see on the web page there is a button named 'Click'. When you click the button then a sentence 'You have clicked the button' will appear on the screen. This means the JavaScript codes written in a separate file is embedded properly and working fine.

On HTML file example8.html you can see <script> tag with 'src' attribute having the value 'script.js' which the name of JavaScript file. Actually the source of JavaScript is fetching on the web page from that file which is embedded with HTML document through a 'Relative path'.

Similarly, look back into example 6 where you can find <script> tag with 'src' attribute having a value 'https://code.jquery.com/jquery-3.5.1.min.js'. It is an example of an absolute URL. To know more about the relative and the absolute path you have to read our another topic HTML5 Tutorial - HTML File Path.

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello programmers! This is a new “JavaScript How To” post which describes ‘How to create Cascading Dropdown Using Plain JS’. This is an example of multiple dependent dropdown lists. Multiple dependent cascading dropdown lists are very useful when you want to display the data in specific categories. You can change drop down options based on another dropdown lists.

First of all, you can click on Try yourself button in below example and check what are we going to create and after that you will find all the require source code of this project. You can also bookmark the repository of progrramers GitHub community where you can find and download the source code of other projects.
If you like our posts please give thumbs up  ๐Ÿ‘ on our Facebook page and also share with your near n dears.



Diagram

In this example we are assuming that there is a school. It has multiple class rooms, every class room contains multiple sections, every section contains multiple subjects and at last every section period will held on a different room. You can see the whole scenario in below image given for the reference.

How to create Cascading Dropdown Using Plain JS - progrramers
How to create Cascading Dropdown Using Plain JS - progrramers

The data will be in tree structure which is used to parse as options in 'SELECT' elements. Let's see the work flow of the final product.

Work Flow 

  1. Classes names only append into select element onload first.
  2. When Selecting a Class then section options will append, available with that class. Same work flow for sections, subjects and rooms.
  3. When Class gets changed then sections, subjects and rooms also get reset. Same work flow for sections, subjects and rooms. Synopsis when a drop down element updated then all next siblings also gets reset.
Now you can copy the code and paste it into your favorite editor and save as ‘anyname.html’ and run into your favorite browser. Analyze the code and if you are getting any problem then feel free to write down into the comment section I’ll try to be more specific into the answers.

You can also get this code on github : How to create Cascading Dropdown Using Plain JS.html

How to create Cascading Dropdown Using Plain JS :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{box-sizing: border-box;font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
        .classform{border: 5px groove #00acf0;background: #c5c5c5;border-radius: 4px;}
        div{padding:5px;}
        .classform>div{width:450px;display:block;margin-left:auto;margin-right:auto;}/*for responsive look*/
        label{background: #00acf0;color:rgb(255, 255, 255);text-shadow:1px 1px 1px #777}
        label,select{display:inline-block;padding:6px;border-radius:3px}
        label{width:100px;}
        select{width:250px;}
    </style>
</head>
<body>
    <div class="classform">
        <div><label for="class">Class: </label> <select name="class" id="class"></select></div>
        <div><label for="section">Section: </label> <select name="section" id="section"></select></div>
        <div><label for="subject">Subject: </label> <select name="subject" id="subject"></select></div>
        <div><label for="room">Room: </label> <select name="room" id="room"></select></div>
    </div><hr/>
    <a href="https://www.facebook.com/theprogrramers">Follow us on Facebook Page</a>
    <script>
        //class structure data in JS object format
        var structure = [
                {label:"class",value:"1",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"1 (B)",child:[]},
                        ]}
                    ]},
                ]},
                {label:"class",value:"2",child:[
                    {label:"section",value:"A",child:[
                        {label:"subject",value:"Science",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"Sanskrit",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                        {label:"subject",value:"English",child:[
                            {label:"room",value:"2 (A)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"B",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Civics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Geography",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                        {label:"subject",value:"Economics",child:[
                            {label:"room",value:"2 (B)",child:[]},
                        ]},
                    ]},
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (C)",child:[]},
                        ]}
                    ]},
                    {label:"section",value:"D",child:[
                        {label:"subject",value:"Math",child:[
                            {label:"room",value:"2 (D)",child:[]},
                        ]}
                    ]}
                ]},
                {label:"class",value:"3",child:[
                    {label:"section",value:"C",child:[
                        {label:"subject",value:"Hindi",child:[
                            {label:"room",value:"3 (A)",child:[]},
                        ]}
                    ]}
                ]},
            ];
        //global variable declaration to store value stepwise
        var cindex, sindex, jindex;
        //calling funfction onload
        window.onload = function(){
            classstrucure(structure, document.querySelectorAll('[name=class]'));
        }
        document.querySelector('body').addEventListener('change',function(e){
            if(e.target.tagName.toLowerCase() == "select"){
                if(e.target.value!==""){
                    //check of nextsibling is null or not 
                    nextsibling = e.target.closest('DIV').nextSibling.nextSibling;
                    if(nextsibling!==null){
                        var _nameAttr=e.target.getAttribute("name");
                        var nextElm = nextsibling.querySelectorAll('SELECT');
                        //for your project only you have to change the attributes name
                        if(_nameAttr==='class'){
                            cindex = structure.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='section'){
                            sindex = structure[cindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child, nextElm);
                        //for your project only you have to change the attributes name
                        }else if(_nameAttr==='subject'){
                            jindex = structure[cindex].child[sindex].child.map(function(i){return i.value}).indexOf(e.target.value);
                            classstrucure(structure[cindex].child[sindex].child[jindex].child, nextElm);
                        }
                    }
                }else{
                    //e.target.value is empty then same function will fire with defferent parameters
                    clearsturcture(e.target.closest('DIV').nextSibling);
                }
            }
        });
        //function create the structure of class step wise
        function classstrucure(data, el){
            //first clear all the select element onload
            //clear all next sibling accept itself
            el.forEach(element => {
                clearsturcture(element.closest('DIV')); 
            });
           // clearsturcture(el[0].closest('DIV'));            
            var opt = '<option value="">--Select--</option>';
            //creating options elemnet
            for(var i=0;i<data.length;i++){
                opt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
            }
            //appending option on each element
            el.forEach(element => {
                element.innerHTML = opt;
            });
        }
        //clear all the next drop down element after itself
        function clearsturcture(parentEl){
            while (parentEl) {
                if(parentEl.tagName !== undefined){
                    //appending initial option on every next sibling
                    parentEl.querySelector('SELECT').innerHTML = '<option>--Select--</option>';
                }
                //looping through last existing sibling and target
                parentEl = parentEl.nextSibling;
            }
        }
    </script>
</body>
</html>
Try Yourself

Related Topics

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

What is MongoDB ObjectId() ?

ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

MongoDB ObjectId is generated by MongoDB Drivers and the Server using a default Algorithm. By default typeof MongoDB ObjectId is object.

MongoDB ObjectId 12 bytes can be break up in to following:

Size Description
4 Bytes 4-byte value representing the seconds since the Unix epoch
3 Bytes 3-byte machine identifier
2 Bytes 2-byte process id
3 Bytes 3-byte counter, starting with a random value

Above is a description of MongoDB ObjectId. Most of the time developers requires unique id of the objects to be rendered on web page. In MongoDB ObjectId are the primary key and best for using as unique ID. Therefore here on the progrramers.com we are giving the solution for ‘How to get lowercase hexadecimal mongodb _id string from ObjectId() in MongoDB ?

Below is the example database which we are using the MongoDB tutorial :



> db.cars.find().toArray();
[
{
"_id" : ObjectId("5d53065a520ea88ac000e981"),
"name" : "Ford",
"color" : "blue",
"weight" : "300KG"
},
{
"_id" : ObjectId("5d53066a520ea88ac000e982"),
"name" : "Opel",
"color" : "red"
},
{
"_id" : ObjectId("5d530677520ea88ac000e983"),
"name" : "Mustang",
"color" : "silver"
},
{
"_id" : ObjectId("5d53069f520ea88ac000e984"),
"name" : "porsche",
"color" : "black"
}
]
>


There are many methods available that can be use to extract the lowercase hexadecimal mongodb _id string from MongoDB ObjectId. We will try to approach all possible ways by using MongoDB methods and JavaScript methods as well.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘valueOf()’ method

Syntax : db.collectionname.findOne()._id.valueOf()

> db.cars.findOne()._id.valueOf();
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object in form of ‘property : value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘str’ method


Syntax : db.collectionname.findOne()._id.str

> db.cars.findOne()._id.str;
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object like above mentioned method e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that ‘str’  method extract the lowercase hexadecimal mongodb _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get value of the ObjectId() in MongoDB using stored functions


There is a special system collection named system.js that can store JavaScript functions for reuse. We can latter call the function using ‘db.eval()’ or ‘db.loadServerScripts()’ methods and get results.

Syntax : db.system.js.save({_id:”functionname”,value:function(parameters){//code here}})

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()")
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>

Explanation

Below example first stores the object in ‘doc’ variable in form of ‘property: value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’. The whole function expression stored in variable and saved in ‘system.js’ collection.
Note : db.eval is deprecated from MongoDB version 3.2 but finally db.eval is removed from MongDB version 4.2 but db.loadServerScripts() method can be used instead

Above stored function is called using ‘db.eval()’ method, below is another method to call stored function in MongoDB shell.

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.loadServerScripts()
> getObjectID()
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>



How to get value of the ObjectId() in MongoDB using plain JavaScript

MongoDB stored functions uses pure JavaScript so it is possible to apply various JavaScript methods to perform a certain task. Now we will see how to get the hexadecimal string in bulk using ‘Array.map()’ function from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){return i._id.valueOf()});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using forEach loop

In this example we will see how to use forEach loop in MongoDB Stored function to extract hexadecimal MngoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... doc.forEach(element => {
... myArr.push(element._id.valueOf());
... });
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using for Loop

In this example we will see how to use for loop in MongoDB Stored function to extract hexadecimal MongoDb _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... for(var i=0;i<doc.length;i++){
... myArr.push(doc[i]._id.valueOf());
... }
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


Mongodb compare Objectid to String



> typeof db.cars.findOne().toString();
string
>


How to get value of the ObjectId() in MongoDB using JavaScript substring

In this example we will see how to use JavaScript substring method in MongoDB Stored function to extract hexadecimal MongoDB _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().substring(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal MongoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().substring(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using JavaScript slice

In this example we will see how to use JavaScript slice method in MongoDB Stored function to extract hexadecimal MongoDb _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().slice(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().slice(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get typeof the ObjectId() in MongoDB using JavaScript

Getting the typeof ObjectId()


> typeof db.cars.findOne()._id;
object
>


How to get the typeof function variable stored in system.js



> typeof db.eval("return getObjectID()");
WARNING: db.eval is deprecated
object
>

How to get the typeof output value



> typeof db.eval("return getObjectID()")[0];
WARNING: db.eval is deprecated
string
>


Related Topics


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello world! We have seen How to do CRUD operation in MongoDB earlier now it’s time to know what are data type which helps us create more efficient database using MongoDB. MongoDB supports more than 15 data types but more important is that what kind of data type is basically used to store the documents.

MongoDB uses bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments called BSON to store documents and make remote procedure calls. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays. BSON also con­tains ex­ten­sions that al­low rep­res­ent­a­tion of data types that are not part of the JSON specifications. Being more specific BSON is a binary format in which zero or more ordered key/value pairs are stored as a single entity. We call this entity a document.

Data type is an important part of Database. When you store the data in database with proper data type it reflects faster performance, therefore data type is important. For e.g. a number can be stored as an integer or string both but if we require numbers later for mathematical calculation then it is good to store the numerical value as integer to get faster mathematical calculations.

In MongoDB each BSON type has both integer and string identifiers as listed in the following table:

Type Number Alias Notes
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”

Some of the most important data types are explained below:

String

String data type is the most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid. MongoDB $regex queries support UTF-8 in the regex string.

NumberDecimal

The decimal BSON data type uses the IEEE 754 decimal128 floating-point numbering format which supports 34 decimal digits (i.e. significant digits) and an exponent range of −6143 to +6144. Decimal 128 datatype is introduced in 3.4 version of MongoDB.

NumberLong (Integer)

The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberLong() wrapper to handle 64-bit integers.

NumberInt (Integer)

The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberInt() constructor to explicitly specify 32-bit integers.

Date

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.


Timestamp

BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. Timestamp values are a 64 bit value where the first 32 bits are a time_t value (seconds since the Unix epoch) and the second 32 bits are an incrementing ordinal for operations within a given second.

Within single mongod instance timestamp values are always unique.

Array

Arrays are the data type that can store single or multiple arrays or values within a single key.

Object

Objects are the data type that used for embedded documents

Object ID

ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

MongoDB Tutorial : How to get lowercase hexadecimal string from MongoDB ObjectId() – Mongodb Objectid Operations.

Boolean

This data type is store Boolean values i.e. True or False.

Min/Max Keys

This type is used to compare a value against the lowest and highest BSON elements. The min and max keys indicate that the system should avoid normal query planning. Instead they construct an index scan where the index bounds are explicitly specified by the values given in min and max.

Null

This data type is used to store null data.

Binary data

This data type is used to store binary form of data.

Regular Expression

This data type is used to store regular expression.

Data Modeling in MongoDB

Unlike SQL databases, where you must determine and declare a table’s schema before inserting data, MongoDB’s collections, by default, does not require its documents to have the same schema. Data in MongoDB has a flexible schema documents in the same collection. They offer to create different fields, structure and data types in and common fields in same collection. This flexibility gives you data-modeling choices to match your application and its performance requirements.


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! In previous chapters we were introduced with MongoDB. Now we know that MongoDB is NoSQL database program that provides a mechanism for storage and retrieval of data in documents of tree structured collections and also we learnt ‘how to create/remove database and collections in MongoDB shell'.



Before we go ahead in this MongoDB Tutorial, let's take a tour on CRUD operation in any database.

What is CRUD Operations in database?

Any database program can perform only four possible operations as mentioned below :
  1. Create or Insert data/ documents in database
  2. Read or Select or Find data/documents from database
  3. Update data/document in database
  4. Delete data/document from database
Create, Read, Update and Delete operations are whole together called CRUD Operations in database program.
In this chapter of MongoDB Tutorial series we will see how to Insert, find, update and delete the documents in MongoDB shell.
So let’s go ahead and see how it is done. In previous post we have created database named ‘cricket’ and inside that database we have created a collection named ‘teamindia’. Now we go to perform CRUD Operations on that database through MongoDB Shell.

MongoDB : Create or insert Operation

Create or insert operations add new document to a collection. If the collection does not currently exist, insert operations will create the collection and add the document. Check the example for your reference

>db.teamindia.insertOne({
name:"Virat Kohali",
role:["Batsman", "Captain"],
batting:"Right-Hand Middle-Order",
bowling:"Right-Arm-Medium",
});
>□


Above is the example of insert single document to a collection. In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
In other words, atomicity means "indivisibility" and "irreducibility”. MongoDB write operations are atomic, only at the level of a single document. If you're modifying multiple subdocuments inside a document the operation is still atomic, but if you're modifying multiple documents, the operation is not atomic.

>db.teamindia.insert({
name:"M.S.Dhoni",
role:["Wicketkeeper", "Batsman"],
batting:"Right-Hand Lower-Middle-Order",
bowling:"Right-Arm-Medium",
});
>□


MongoDB shell provides following Methods to insert document in a collection :
  • db.collectionname.insert() – insert one or more document at same time
  • db.collectionname.inserOne() – insert one document at a time (Introduced in MongoDB 3.2)
  • db.collectionname.insertMany() – insert multiple document at a time (Introduced in MongoDB 3.2)

Mathod: db.collectionname.insert();

Using this method you can insert one or multiple document at a single write. It takes single data as a JavaScript object. MongoDB provides clients the ability to perform write operations in bulk. In this method, it takes array of JavaScript objects to insert multiple data at single write. Must check the below example carefully :
Example of db.collectionname.insert()

Mathod: db.collectionname.insertOne();

Using this method you can insert single document in a collections. It takes single data as a JavaScript object.
Example

Mathod: db.collectionname.insertMany();

Using this method you can insert one or multiple documents at a single write. Like db.collectionname.insert() method this (db.collectionname.insertMany()) method also takes array of JavaScript objects to insert multiple data at single write.


>db.teamindia.insertMany([
{
name:"Sikhar Dhawan",
role:["Batsman"],
batting:"Left-Hand Opener",
},
{
name:"Rohit Sharma",
role:["Batsman", "Vice Captain"],
batting:"Right-Hand Opener",
},
{
name:"Kedar Jadav",
role:["Allrounder","Batsman", "Bowler"],
batting:"Right-Hand Middle-Order",
bowling: "Right-Arm-Slinger-Off-Break"
},
{
name:"Rabindra Jadeja",
role:["Allrounder","Batsman", "Bowler"],
batting:"Left-Hand Lower-Middle-Order",
bowling: "Left-Arm-Off-Break"
},
{
name:"Jasprit Bumrah",
role:["Batsman", "Bowler"],
batting:"Right-Hand Talender",
bowling: "Right-Arm-Fast-Medium"
},
]);
>□


Check the above example carefully, Data in MongoDB has a flexible schema documents in the same collection. They 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.You can see in the above example.

With MongoDB, you may embed related data in a single structure or document. These schema 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.

Difference between db.collectionname.insert() and db.collectionname.insertMany() : progrramers explanation

The major difference between these two methods is the output response value after performing insert and insertmany operations. When inserting multiple document using insert method, you will get the response as BulkWriteResult() in JSON format (see in the below image) while inserting multiple document using insertMany you will get the acknowledge status as true/false and an array of ObjectId of inserted documents (see in the below image).

MongoDB Tutorial - difference between insert and insertMany
MongoDB Tutorial - difference between insert and insertMany


Note : The output response value is most important thing while you are working as professional. Professional programmers use the methods as per their requirement of output (return) values. Progrramers also suggest using the insert method as per requirement of response value.

MongoDB : Read or find Operation

Read or find operation retrieves the documents from collections.
MongoDB shell provides following Methods to query document in collections :
  • db.collectionname.find(); - find entire document(s) from a collection at a time
  • db.collectionname.findOne(); - find the single document from a collection (Introduced in MongoDB 3.2)

Mathod : db.collectionname.find();

Using this method you can retrieve the document in a collection and it returns a cursor of the selected documents. You can specify query criteria, projection and other filters to this method like motioned in below example :

>db.teamindia.find()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
}

>□

While dealing with multiple output results, we can arrange

Method : db.collectionname.findOne();

Using this method you can retrieves the document as per query criteria and it returns a single document. If the criteria matches with multiple records it returns first document in collection according to the natural order which reflects the order of documents on the disk.

>db.teamindia.findOne()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}

>□


MongoDB : Update Operation

Using update operation you can modify existing document in a collection. MongoDB provides the following methods to update documents of a collection:
  • db.collection.update (); - Update document(s) in a collection
  • db.collection.updateOne(); - Update single document in a collection (Introduced in MongoDB 3.2)
  • db.collection.updateMany(); - Update multiple document in a collection (Introduced in MongoDB 3.2)
  • db.collection.replaceOne(); - Replace the entire content of a document except for the _id field (Introduced in MongoDB 3.2)

Method : db.collectionname.updateOne();

Using this method you can update single document in a collection. It also takes multiple parameters as filter criteria. When filter criteria matches with multiple document then it updates the first matching document in the collection.

>db.teamindia.findOne({batting : "Left-Hand Opener"})
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}
> db.teamindia.updateOne({"name" : "Sikhar Dhawan"},{$set:
{"batting" : "Right-Hand Opener"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.teamindia.findOne({batting : "Left-Hand Opener"})
null
>□

Method : db.collectionname.updateMany();

Using this method you can update multiple documents in a collection. It also takes multiple parameters as filter criteria. When filter criteria matches with multiple document then it updates the all matching document in the collection.

> db.teamindia.find({"batting" : "Right-Hand Opener"}).pretty()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Right-Hand Opener"
}
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
}
> db.teamindia.updateMany({"batting" : "Right-Hand Opener"},{$set :
{"batting" : "Left-Hand Opener"}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
>□


Method : db.collectionname.replaceOne();

With this method your replace single document in a collection. It also takes multiple parameters as filter criteria like db.collectionname.updateOne(). When filter criteria matches with multiple document then it replaces the first matching document in the collection.

> db.teamindia.find({"name" : "Rohit Sharma"}).pretty()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Left-Hand Opener"
}
> db.teamindia.replaceOne({"name" : "Rohit Sharma"},{"name" : "Rohit Kohali",
"batting"
: "Right-Hand Opener","bowling":"Right-Arm Off Breack"})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>□



Note : All above update methods take special Boolean parameter. If upsert : true then new document will added to collections if no match found with filter criteria or if match found then the existing document will be update.


MongoDB: Delete Operation

Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection.
  • collection.remove(); - Removes single and multiple documents from a collection
  • collection.deleteOne(); - Removes single document form a collection (Introduced in MongoDB 3.2)
  • collection.deleteMany(); - Removes multiple or entire documents form a collection (Introduced in MongoDB 3.2)
In MongoDB, delete operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to remove. These filters use the same syntax as read operations.

Method: db.collectionname.remove();

In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.

>db.teamindia.remove({"name" : "Rohit Sharma"});
WriteResult({ "nRemoved" : 1 })
>□


Removing Single Document from a collection

To remove a single document, call the remove() method with the justOne parameter set to true or 1.

Method: db.collectionname.deleteOne();

This method deletes the first document that matches the filter. You can use the unique index such as _id field for exact match.

>db.teamindia.deleteOne({"name" : "Kedar Jadav"});
WriteResult({ "nRemoved" : 1 })
>□

Method: db.collectionname.deleteMany();

This method deletes the entire documents that match the filter.

>db.teamindia.deleteMany({"batting" : "Right-Hand Talender"})
{ "acknowledged" : true, "deletedCount" : 3 }
>□

MongoDB Tutorial : How to get lowercase hexadecimal string from MongoDB ObjectId() – Mongodb Objectid Operations.