0% found this document useful (0 votes)
66 views

Studocu Unit-4

Uploaded by

Bhargav Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Studocu Unit-4

Uploaded by

Bhargav Vijay
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

lOMoARcPSD|34807602

UNIT-4 MSD Notes

Mean stack development (Jawaharlal Nehru Technological University, Kakinada)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)
lOMoARcPSD|34807602

1 UNIT-4 MSD

UNIT-IV:
Typescript: Installing TypeScript, Basics of TypeScript, Function, Parameter Types and Return Types,
Arrow Function, Function Types, Optional and Default Parameters, Rest Parameter, Creating an
Interface, Duck Typing, Function Types, Extending Interfaces, Classes, Constructor, Access Modifiers,
Properties and Methods, Creating and using Namespaces, Creating and using Modules, Module Formats
and Loaders, Module Vs Namespace, What is Generics, What are Type Parameters, Generic Functions,
Generic Constraints.
MongoDB: Introduction Module Overview, Document Database Overview, Understanding JSON,
MongoDB Structure and Architecture, MongoDB Remote Management, Installing MongoDB on the local
computer (Mac or Windows), Introduction to MongoDB Cloud, Create MongoDB Atlas Cluster, GUI
tools Overview, Install and Configure MongoDB Compass, Introduction to the MongoDB Shell,
MongoDB Shell JavaScript Engine, MongoDB Shell JavaScript Syntax, Introduction to the MongoDB
Data Types, Introduction to the CRUD Operations on documents, Create and Delete Databases and
Collections, Introduction to MongoDB Queries.

………………………………………………………………………………………………………………………………………………….

Typescript:(introduction)
TypeScript is an open-source, object-oriented programing language, which is developed and
maintained by Microsoft under the Apache 2 license. It was introduced by Anders Hejlsberg, a core member of the
development team of C# language. TypeScript is a strongly typed superset of JavaScript which compiles to plain
JavaScript. It is a language for application-scale JavaScript development, which can be executed on any browser, any
Host, and any Operating System. TypeScript is not directly run on the browser. It needs a compiler to compile and
generate in JavaScript file. TypeScript is the ES6 version of JavaScript with some additional features.

What is TypeScript?
TypeScript is an open-source pure object-oriented programing language. It is a
strongly typed superset of JavaScript which compiles to plain JavaScript. It contains all elements of the
JavaScript. It is a language designed for large-scale JavaScript application development, which can be
executed on any browser, any Host, and any Operating System. The TypeScript is a language as well as a set
of tools. TypeScript is the ES6 version of JavaScript with some additional features.

TypeScript cannot run directly on the browser. It needs a compiler to compile the file and generate it in
JavaScript file, which can run directly on the browser. The TypeScript source file is in ".ts" extension. We
can use any valid ".js" file by renaming it to ".ts" file. TypeScript uses TSC (TypeScript Compiler) compiler,
which convert Typescript code (.ts file) to JavaScript (.js file).

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

2 UNIT-4 MSD

Why use TypeScript?


We use TypeScript because of the following benefits.

 TypeScript supports Static typing, Strongly type, Modules, Optional Parameters, etc.
 TypeScript supports object-oriented programming features such as classes, interfaces, inheritance,
generics, etc.
 TypeScript is fast, simple, and most importantly, easy to learn.
 TypeScript provides the error-checking feature at compilation time. It will compile the code, and if
any error found, then it highlighted the mistakes before the script is run.
 TypeScript supports all JavaScript libraries because it is the superset of JavaScript.

TypeScript Vs. JavaScript


SN JavaScript TypeScript
It doesn't support strongly typed or static
1. It supports strongly typed or static typing feature.
typing.
2. Netscape developed it in 1995. Anders Hejlsberg developed it in 2012.
3. JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.
4. It is directly run on the browser. It is not directly run on the browser.
It supports object-oriented programming concept like
5. It is just a scripting language.
classes, interfaces, inheritance, generics, etc.
6. It doesn't support optional parameters. It supports optional parameters.
It is interpreted language that's why it It compiles the code and highlighted errors during the
7.
highlighted the errors at runtime. development time.
8. JavaScript doesn't support modules. TypeScript gives support for modules.
9. In this, number, string are the objects. In this, number, string are the interface.
10. JavaScript doesn't support generics. TypeScript supports generics.
Example:
<script>
function addNumbers(a, b) {
Example:
function addNumbers(a, b) {
return a + b;
return a + b;
. }
}
var sum = addNumbers(15, 25);
var sum = addNumbers(15, 25);
document.write('Sum of the numbers
console.log('Sum of the numbers is: ' + sum);
is: ' + sum);
</script>

Installing TypeScript:

To install TypeScript, go to the official site of TypeScript ( http://www.typescriptlang.org/


) and follow the steps mentioned there to download TypeScript.

As mentioned on the official site, you need to install Node.js.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

3 UNIT-4 MSD

Install Node.js from the official site of Node.js ( https://nodejs.org/en/) or Software


Center.

Open a Node.js command prompt and check whether node and npm are installed in
your machine by using "node -v " and "npm -v" commands.

npm is a command-line tool that comes along with Node.js installation with which you
can download node modules. TypeScript is also such a node module that can be
installed using npm.

Open Node.js command prompt, execute the below commands as shown below to
download the TypeScript node module from the local Infosys repository.

Setup the registry:

1. npm config set registry


https://infyartifactory.ad.infosys.com/artifactory/api/npm/n

pm/

In the same Node.js command prompt, type the "npm i –g typescript" command to
download the TypeScript module from the repository.

On successful execution of above command, the TypeScript module will get


downloaded under folder
C:\Users\<<username>>\AppData\Roaming\npm\node_modules\typescript as shown
below.

In the same command prompt check for TypeScript installation as below:

1. tsc -v
2. //or

3. tsc --version

Output showing version number indicates the successful installation of the TypeScript
module.

Alternatively, you can also use TypeScript online playground editor in this case, you
should be always connected to good Internet.

To configure TypeScript with different IDEs. Here are a few links for IDE configuration
for TypeScript:

 VisualStudio Code: https://code.visualstudio.com/Docs/languages/typescript


 Eclipse IDE: https://github.com/palantir/eclipse-typescript
 Visual Studio 2015: https://angular.io/guide/visual-studio-2015

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

4 UNIT-4 MSD

First TypeScript Application:

To start with the first application in TypeScript, create a file hello_typescript.ts under a
folder. In the ts file give a console.log statement and save it.

From the Node.js command prompt, navigate to the directory in which the ts file resides
and compile the ts file using the tsc command.

After compilation of the TypeScript file, the corresponding JavaScript file gets
generated.

To run the generated JavaScript file, use the node command from the command line or
include it in an HTML page using the script tag and render it in the browser.

Basics of TypeScript:
Consider the below page of the Mobile Cart application. The information such as
mobile phone name, price, status on the availability of the mobile, discounts is
displayed on the page. It also displays different price ranges as GoldPlatinum,
PinkGold, SilverTitanium.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

5 UNIT-4 MSD

Each of the information getting displayed has a specific type. For example, the price
can only be numeric and the mobile name can only be a string.

There should be a mechanism using which you can restrict the values being rendered
on the page.

Sometimes it is preferred to have a text instead of numeric values to represent some


information. For example, on the above page instead of categorizing the mobiles based
on their prices, you can prefer to remember them as some text like GoldPlatinum,
PinkGold, etc.

TypeScript is a static typed language that allows us to declare variables of various data
types so that you ensure only the desired type of data being used in the application.

Let us discuss declaring variables and basic data types supported by TypeScript.

Declaring Variables:

Declaration of a variable is used to assign a data type and an identifier to a variable.


Declaration of variables in TypeScript is like JavaScript variable declaration.

Below are the three declaration types supported in TypeScript.

Data Type Explanation


 Variable declared with this type would have function scope.
 They can be re-assigned and re-defined.
var  When a variable declared outside the function, it would have global scope
and automatically attaches itself to the window object.

 Variable declared with this type would have a block-level scope.


let  They can be re-assigned and cannot be redefined.

 Variable declared with this type would have a block-level scope.


const  They can be neither re-assigned nor re-defined.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

6 UNIT-4 MSD

Basic Types :
Data type mentions the type of value assigned to a variable. It is used for variable
declarations.

Since TypeScript supports static typing, the data type of the variable can be
determined at the compilation time itself.

There are variables of different types in TypeScript code based on the data type used
while declaring the variable.

boolean:

boolean is a data type that accepts only true or false as a value for the variable it is
been declared.

In a shopping cart application, you can use a boolean type variable to check for the
product availability, to show/hide the product image, etc.

number:

number type represents numeric values. All TypeScript numbers are floating-point
values.

In a shopping cart application, you can use number type to declare the Id of a product,
price of a product, etc.

string:

A string is used to assign textual values or template strings. String values are written in
quotes – single or double.

In a shopping cart application, you can use string type to declare variables like
productName, productType, etc.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

7 UNIT-4 MSD

any:

any type is used to declare a variable whose type can be determined dynamically at
runtime with the value supplied to it. If no type annotation is mentioned while declaring
the variable, any type will be assigned by default.

In a shopping cart application, you can use any type to declare a variable like
screenSize of a Tablet.

void:

void type represents undefined as the value. the undefined value represents "no value".
A variable can be declared with void type as below:

Functions:
Consider the below page that displays the list of mobile phones
available. For each mobile in the list, you can see its image, name, price, and
availability status. The property ‘name’ of the mobile is clickable.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

8 UNIT-4 MSD

When the mobile name link is clicked, the user is navigated to


the next screen which shows the details specific to the phone selected. The details
such as different colors in which the phone is available, price of mobile according to the
color selected, description of the phone, availability status, and discounts if any.

Users can click on each color to view the mobile image for that color. The Price
corresponding to the color selected can also be shown. For example: On click of
PinkGold the below screen should be rendered:

This requirement is implemented using the function concept in TypeScript that


helps us to implement business logic and event handlers. Let us discuss functions in
TypeScript.

Function in TypeScript Vs JavaScript:

 A function is a block of statements to perform a particular task.


 A sequence of statements written within function forms function body.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

9 UNIT-4 MSD

 Functions are executed when it is invoked by a function call. Values can be


passed to a function as function parameters and the function returns a value.
 Functions in TypeScript are like functions in JavaScript with some additional
features.

TypeScript JavaScript
Types: Supports Do not support
Required and optional parameters: Supports All parameters are optional
Function overloading: Supports Do not support
Arrow functions: Supports Supported with ES2015
Default parameters: Supports Supported with ES2015
Rest parameters: Supports Supported with ES2015

Parameter Types and Return Types:

The parameter type is the data type of the parameter and the return type is the data
type of the returned value from the function.

With the TypeScript function, you can add types to the parameter passed to the
function and the function return types.

While defining the function, return the data with the same type as the function return
type. While invoking the function you need to pass the data with the same data type as
the function parameter type, or else it will throw a compilation error.

Arrow Function:
Arrow function is a concise way of writing a function. Whenever you need a function to
be written within a loop, the arrow function will be the opt choice.

Do not use the function keyword to define an arrow function.

In a shopping cart application, you can use the arrow function to perform filtering,
sorting, searching operations, and so on.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

10 UNIT-4 MSD

Function Types :
Function types are a combination of parameter types and return type. Functions can be
assigned to variables.

While assigning a function to a variable make sure that the variable declaration is the
same as the assigned function’s return type.

Optional and Default Parameters:


TypeScript treats every function parameter as mandatory. So when a function is
compiled, the compiler will check whether there is a value supplied to all the
parameters of the function, or else it will throw a compilation error.

Consider the code below:

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

11 UNIT-4 MSD

In the above example, you have tried to invoke a function with only a single parameter,
whereas the definition of the function accepts two parameters. Hence, it will throw a
compilation error. Also, optional parameter can be used to tackle this issue.

The Optional parameter is used to make a parameter, optional in a function while


invoking the function.

If you rewrite the previous code using an optional parameter, it looks like the below:

An Optional parameter must appear after all the mandatory parameters of a function.

Default parameter is used to assign the default value to a function parameter.

If the user does not provide a value for a function parameter or provide the value as
undefined for it while invoking the function, the default value assigned will be
considered.

If the default parameter comes before a required parameter, you need to explicitly pass
undefined as the value to get the default value.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

12 UNIT-4 MSD

Rest Parameter:
Rest Parameter is used to pass multiple values to a single parameter of a function. It
accepts zero or more values for a single parameter.

 Rest Parameter should be declared as an array.


 Precede the parameter to be made as rest parameter with triple dots.
 Rest parameter should be the last parameter in the function parameter list.

What is an Interface?:
An interface in TypeScript is used to define contracts within the code.

 Interfaces are used to enforce type checking by defining contracts.


 It is a collection of properties and method declarations.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

13 UNIT-4 MSD

 Interfaces are not supported in JavaScript and will get removed from the
generated JavaScript.
 Interfaces are mainly used to identify issues upfront as we proceed with coding.

Duck Typing:
Duck-Typing is a rule for checking the type compatibility for more complex variable
types.

TypeScript compiler uses the duck-typing method to compare one object with the other
by comparing that both the objects have the same properties with the same data types.

TypeScript interface uses the same duck typing method to enforce type restriction. If an
object that has been assigned as an interface contains more properties than the
interface mentioned properties, it will be accepted as an interface type and additional
properties will be ignored for type checking

Let us rewrite the previous example to a pass additional parameter.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

14 UNIT-4 MSD

Function Types :
Interfaces can be used to define the structure of functions like defining structure of
objects.

Once the interface for a function type is declared, you can declare variables of that type
and assign functions to the variable if the function matches the signature defined in the
interface.

Function type interface is used to enforce the same number and type of parameters to
any function which is been declared with the function type interface.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

15 UNIT-4 MSD

Extending Interfaces:
An interface can be extended from an already existing one using the extends
keyword.

In the code below, extend the productList interface from both the Category interface
and Product interface.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

16 UNIT-4 MSD

Class Types:
Make use of the interface to define class types to explicitly enforce
that a class meets a particular contract. Use implements keyword to implement
interface inside a class.

To enforce interface type on a class, while instantiating an object of a class declare it


using the interface type.

The only interface declared functions and properties will be available with the
instantiated object.

Why Class?
Classes are used to create reusable components. Till the ES5
version of JavaScript, you do not have a class concept as such. For implementing
reusable components, use functions and prototype-based inheritance. TypeScript
provides an option for the developers to use object-oriented programming with the help
of classes.

In the Mobile Cart application, you can use a class to define the product and create
various objects of different products. In the below screen, creating different objects of
product and rendering the details

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

17 UNIT-4 MSD

What is a Class?:
 Class is a template from which objects can be created.
 It provides behavior and state storage.
 It is meant for implementing reusable functionality.
 Use a class keyword to create a class.

Constructor :
A constructor is a function that gets executed automatically whenever an instance of a
class is created using a new keyword.

 To create a constructor, a function with the name as a "constructor" is used.


 A class can hold a maximum of one constructor method per class.
 You can use optional parameters with a constructor function as well.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

18 UNIT-4 MSD

Access Modifiers:
Access modifiers are used to provide certain restriction of accessing the properties and
methods outside the class.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

19 UNIT-4 MSD

Properties and Methods:


Instead of declaring instance variables and then passing parameters to the constructor
and initializing it, you can reduce the code by adding access specifiers to the
parameters passed to the constructor.

Consider the below code:

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

20 UNIT-4 MSD

Instead of this declare the parameter itself with any of the access modifiers and reduce
the lines of code used for the initialization.

Let us rewrite the above code:

TypeScript provides an option to add getters/setters to control accessing the members


outside the class or modifying the same.

There is no direct option available to access private members outside the class but use
accessors in TypeScript for the same.

If you need to access private properties outside the class, you can use the getter and if
you need to update the value of the private property, you can use the setter.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

21 UNIT-4 MSD

What is a Namespace?
A Namespace is used to group functions, classes, or interfaces under a common name.

 The content of namespaces is hidden by default unless they are exported.


 Use nested namespaces if required.
 The function or any construct which is not exported cannot be accessible outside
the namespace.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

22 UNIT-4 MSD

Creating and using Namespaces


In the below example, create a namespace called Utility and group a function
MaxDiscountAllowed and a nested namespace called payment inside it.

To import the namespace and use it, make use of the triple slash reference tag.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

23 UNIT-4 MSD

bvcbvb

The file in which the namespace is declared and the file which uses the namespace to
be compiled together. It is preferable to group the output together in a single file. You
have an option to do that by using the --outFile keyword.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

24 UNIT-4 MSD

What is a Module?
Modules help us in grouping a set of functionalities under a common name. The
content of modules cannot be accessible outside unless exported.

Precede export keyword to the function, class, interface, etc.. which you need to export
from a module.

Creating and using Modules:


The constructs of a module can be exported by one of the below approaches:

1. Adding an export keyword in front of a function or a class or an interface

2. Adding an export keyword to a block of statements

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

25 UNIT-4 MSD

Using the import keyword, you can import a module within another module or another
TypeScript file. Provide the file name as the module name while importing.

Once the module is imported, make use of the classes and other constructs exported
from the module.

Also, alias names can be used while importing/exporting a module.

To compile the modules and the file which is using the module, compile them together
using the tsc command.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

26 UNIT-4 MSD

Module Formats and Loaders:


Module format is the syntax that is used to define a module in JavaScript.

Modules in TypeScript can be compiled to one of the module formats given below:

Commonly we compile the modular code in TypeScript to ES2015 format by using the -
-module ES2015 keyword while performing the compilation.

If none of the formats are mentioned in the compiler option, by default CommonJS
module format will be the one that gets generated while compiling modules in
TypeScript.

A module loader interprets and loads a module written in a certain module format as
well as helps in importing all the dependent modules into developer working
environment. At the runtime, they play a very vital role in loading and configuring all
needed dependencies modules before executing any linked module.

The most commonly used module loaders in JavaScript are:

SystemJS module loader for modules in AMD, CommonJS, UMD, or System.register


format

Require.js module loader for modules in AMD format.

On-demand functionalities can be loaded by Modules, which is known as lazy loading.


By using this feature while executing our application all the declared modules are not
loaded at that moment, it only loads needed modules that are needed by the user to
render the initial look of the application on the first load. Due to this

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

27 UNIT-4 MSD

concept performance of the application can be enhanced as the initial startup time of
the application automatically decreases.

Module Vs Namespace:
Module Namespace
Organizes code Organizes code
Have native support with Node.js module loader.
All modern browsers are supported with a No special loader required
module loader.
ES2015 does not have a Namespace concept.
Supports ES2015 module syntax It is mainly used to prevent global namespace
pollution.
Suited for large-scale applications Suited for small-scale applications

Why Generics?:
Generics helps us to avoid writing the same code again for different data types.

In TypeScript, generics are used along :

 with function to invoke the same code with different type arguments
 with Array to access the same array declaration with a different set of typed
values
 with Interface to implement the same interface declaration by different classes
with different types
 with a class to access the same class with different types while instantiating it

What is Generics?
Generics is a concept using which we can make the same code work for multiple types.

It accepts type parameters for each invocation of a function or a class or an interface so


that the same code can be used for multiple types.

Consider the below code where you implement a similar function for two different types
of data:

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

28 UNIT-4 MSD

Avoid writing the same code again for different types using generics. Let us rewrite the
above code using generics:

What are Type Parameters?


Type Parameters are used to specify the type, a generic will work over.

They are listed using an angle bracket<>.

The actual type will be provided while invoking function or instance creation.

Consider a generic function given below:

To access this function with different types you will use the below code:

Generic Functions:
Generic functions are functions declared with generic types.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

29 UNIT-4 MSD

Declaring generic function is done using the type parameter and using the same type
variable for the parameter and the return type.

Generic Constraints :
Generic constraints are used to add constraints to the generic type.

Generic constraints are added using the 'extends' keyword.

Consider the below code:

Here you are trying to access the length property of the function type parameter.

Since the parameter type will get resolved only at run time, this line will throw
compilation

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

30 UNIT-4 MSD

If you need to access a property on the type parameter, add those properties in an
interface or class and extend the type parameter from the declared interface or class.

Let us rewrite the previous code:

To invoke this generic function, you can pass any parameter which has a length
property.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

31 UNIT-4 MSD

PART-B

MongoDB: Introduction Module Overview, Document Database Overview, Understanding JSON,


MongoDB Structure and Architecture, MongoDB Remote Management, Installing MongoDB on the local
computer (Mac or Windows), Introduction to MongoDB Cloud, Create MongoDB Atlas Cluster, GUI
tools Overview, Install and Configure MongoDB Compass, Introduction to the MongoDB Shell,
MongoDB Shell JavaScript Engine, MongoDB Shell JavaScript Syntax, Introduction to the MongoDB
Data Types, Introduction to the CRUD Operations on documents, Create and Delete Databases and
Collections, Introduction to MongoDB Queries.

…………………………………………………………………………………………………………………………………………………….

Introduction Module Overview:

In simple words, you can say that - Mongo DB is a document-oriented database. It is an open source
product, developed and supported by a company named 10gen.

MongoDB is available under General Public license for free, and it is also available under Commercial
license from the manufacturer.

The manufacturing company 10gen has defined MongoDB as:

"MongoDB is a scalable, open source, high performance, document-oriented database." - 10gen

MongoDB was designed to work with commodity servers. Now it is used by the company of all sizes, across
all industry.

History of MongoDB
The initial development of MongoDB began in 2007 when the company was building a platform as a service
similar to window azure.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

32 UNIT-4 MSD

Window azure is a cloud computing platform and infrastructure, created by Microsoft, to build, deploy and
manage applications and service through a global network.

MongoDB was developed by a NewYork based organization named 10gen which is now known as
MongoDB Inc. It was initially developed as a PAAS (Platform as a Service). Later in 2009, it is introduced
in the market as an open source database server that was maintained and supported by MongoDB Inc.

The first ready production of MongoDB has been considered from version 1.4 which was released in March
2010.

MongoDB2.4.9 was the latest and stable version which was released on January 10, 2014.

Purpose of Building MongoDB


It may be a very genuine question that - "what was the need of MongoDB although there were many
databases in action?"

There is a simple answer:

All the modern applications require big data, fast features development, flexible deployment, and the older
database systems not competent enough, so the MongoDB was needed.

The primary purpose of building MongoDB is:

o Scalability
o Performance
o High Availability
o Scaling from single server deployments to large, complex multi-site architectures.
o Key points of MongoDB
o Develop Faster
o Deploy Easier
o Scale Bigger

First of all, we should know what is document oriented database?

Example of Document-Oriented Database


MongoDB is a document-oriented database. It is a key feature of MongoDB. It offers a document-oriented
storage. It is very simple you can program it easily.

MongoDB stores data as documents, so it is known as document-oriented database.

FirstName = "John",
Address = "Detroit",
Spouse = [{Name: "Angela"}].
FirstName ="John",

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

33 UNIT-4 MSD

Address = "Wick"

There are two different documents (separated by ".").

Storing data in this manner is called as document-oriented database.

Mongo DB falls into a class of databases that calls Document Oriented Databases. There is also a broad
category of database known as No SQL Databases.

Features of MongoDB
These are some important features of MongoDB:

1. Support ad hoc queries

In MongoDB, you can search by field, range query and it also supports regular expression searches.

2. Indexing

You can index any field in a document.

3. Replication

MongoDB supports Master Slave replication.

A master can perform Reads and Writes and a Slave copies data from the master and can only be used for
reads or back up (not writes)

4. Duplication of data

MongoDB can run over multiple servers. The data is duplicated to keep the system up and also keep its
running condition in case of hardware failure.

5. Load balancing

It has an automatic load balancing configuration because of data placed in shards.

6. Supports map reduce and aggregation tools.

7. Uses JavaScript instead of Procedures.

8. It is a schema-less database written in C++.

9. Provides high performance.

10. Stores files of any size easily without complicating your stack.

11. Easy to administer in the case of failures.

Document Database Overview:

Document Database
Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)
lOMoARcPSD|34807602

34 UNIT-4 MSD

A record in MongoDB is a document, which is a data structure composed


of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields
may include other documents, arrays, and arrays of documents.

The advantages of using documents are:

 Documents correspond to native data types in many programming languages.

 Embedded documents and arrays reduce need for expensive joins.

 Dynamic schema supports fluent polymorphism.

Understanding JSON:
In MongoDB, JSON is the primary data format for storing and working with data.
MongoDB stores data in a binary-encoded format called BSON (Binary JSON), which is a superset of
JSON that includes additional data types and features.

MongoDB uses JSON-like documents to represent data in the database.


These documents are stored in collections, which are similar to tables in a traditional relational
database. Each document is a self-contained unit that represents a single instance of data, and can
contain any number of fields, with each field consisting of a key-value pair.

JSON Format
{
"name1": value1,
"name2": value2,
"name3": value3,
.
.
.
"nameN": valueN

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

35 UNIT-4 MSD

}
JSON – JavaScript Object Notation
Example:
{
"name":"Joes",
"age":35,
"gender":"male",
"married":true,
"address":{
"street":"cherry Road",
"city":"Salem",
"state":"Tamil Nadu"
},
"hobbies":[
{
"name":"Cooking"
},
{
"name":"Sports"
}
]
}

JSON Data Types:

JSON supports 6 Data Types


• String
• Number
• Boolean
• Array
• Object
• Nul

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

36 UNIT-4 MSD

Example:

{
"string": "That's a sample string",
"number": 6,
"boolean": true,
"array": ["first", "second", "third"],
"object": {
"key1": 1,
"key2": "Sample",
"key3": true,
"key4": [1, 2, 3],
"key5": {
"nestedObjKey1": 10,
"nestedObjKey2": false
}
},
"null": null
}

Mongo DB Structure and Architecture :

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

37 UNIT-4 MSD

The MongoDB Structure

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

38 UNIT-4 MSD

MongoDB architecture follows a flexible data model. Unlike RDBMS, which


mandates a schema declaration before inserting data, MongoDB does not enforce a
fixed document structure.
Terminologies
Fields
A key-value pair in a document, it is the counterpart of a column in relational
databases
Document
This is the equivalent of a record in RDBMS
Collections
A group of documents is called a collection. This is analogous to an RDBMS table.

install MongoDB on Windows:


Firstly you will have to download the latest release of MongoDB:

How to download MongoDB


You can download an appropriate version of MongoDB which your system supports,
from the link "http://www.mongodb.org/downloads" to install the MongoDB on Windows. You should
choose correct version of MongoDB acording to your computer's Window. If you are not sure what Window
version are you using, open your command prompt and execute this command:

C:\ wmic os get osarchitecture

MongoDB for Windows Server 2008 R2 edition


This version of MongoDB runs only on Window Server 2008 R2, Window7 64 bit, and the newer version of
windows. You can't operate it on older version of windows.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

39 UNIT-4 MSD

MongoDb for 64 bit Windows


This version of MongoDB runs only on newer version of Windows contains 64 bit operating syste Pau

for example: Window Server 2008 R2, Window 7 64 bit etc.

MongoDb for 32 bit Windows


This version of MongoDB runs on only 32 bit windows. 32 bit version of MongoDB is generally used in
testing and development purposes because it supports databases smaller than 2 GB.

How to install the downloaded file


In Window explorer, locate the downloaded MongoDB msi file, double click on that file and follow the
instructions appears on the screen. These instructions will guide you to complete the installation process.

Note: If you want to move the MongoDB folder from default position to another position, it is necessary
to issue the move command as an administrator. let us take an example to move the folder to C :
\mongodb:
Select Start Menu > All Programs > Accessories

You can install MongoDB in any folder because it is self contained and does not have any other system
dependency.

How to set up the MongoDB environment


A data directory is required in MongoDB to store all the information. Its by default data directory path is
\data\db. you can create this folder by command prompt.

md\data\db

For example:

If you want to start MongoDB, run mongod.exe

You can do it from command prompt.

C:\Program Files\MongoDB\bin\mongod.exe

This will start the mongoDB database process. If you get a message "waiting for connection" in the console
output, it indicates that the mongodb.exe process is running successfully.

For example:

When you connect to the MongoDB through the mongo.exe shell, you should follow these steps:

1. Open another command prompt.


2. At the time of connecting, specify the data directory if necessary.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

40 UNIT-4 MSD

Note: If you use the default data directory while MongoDB installation, there is no need to specify the
data directory.

For example:

C:\mongodb\bin\mongo.exe

If you use the different data directory while MongoDB installation, specify the directory when connecting.

For example:

C:\mongodb\bin\mongod.exe-- dbpath d:\test\mongodb\data

If you have spaces in your path, enclose the entire path in double space.

For example:

C:\mongodb\bin\mongod.exe-- dbpath "d: \ test\mongodb\data"

How to configure directory and files


First to create a configuration file and a directory path for MongoDB log output after that create a specific
directory for MongoDB log files.

Introduction to MongoDB Cloud:

Create MongoDB Atlas:

MongoDB Atlas
MongoDB Atlas is a cloud service by MongoDB. It is built for developers who'd rather spend time building
apps than managing databases. This service is available on AWS, Azure, and GCP.

It is the worldwide cloud database service for modern applications that give best-in-class automation and
proven practices guarantee availability, scalability, and compliance with the foremost demanding data
security and privacy standards. We can use MongoDB's robust ecosystem of drivers, integrations, and tools
to create faster and spend less time managing our database.

Advantages of MongoDB Atlas

o Global clusters for world-class applications: Using MongoDB Atlas, we are free to choose the cloud
partner and ecosystem that fit our business strategy.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

41 UNIT-4 MSD

o Secure for sensitive data: It offers built-in security controls for all our data. It enables enterprise-grade
features to integrate with our existing security protocols and compliance standard.
o Designed for developer productivity: MongoDB Atlas moves faster with general tools to work with our data
and a platform of services that makes it easy to build, secure, and extend applications that run on MongoDB.
o Reliable for mission-critical workload: It is built with distributed fault tolerance and automated data
recovery.
o Built for optimal performance: It makes it easy to scale our databases in any direction. We can get more out
of our existing resources with performance optimization tools and real-time visibility into database metrics.
o Managed for operational efficiency: It comes with built-in operational best practices, so we can focus on
delivering business value and accelerating application development instead of managing databases.

Create an Atlas Account and deploying a Free Tier Cluster


Step 1: Go to https://www.mongodb.com/cloud/atlas to register for an Atlas account to host your data.

Step 2: When you click on Start Free, you will be redirected to the Registration form for an account on the
MongoDB Atlas.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

42 UNIT-4 MSD

Step 3: Select Starter Clusters and click create a Cluster. The Starter cluster includes the M0, M2, and M5
cluster tiers. These low-cost clusters are suitable for users who are learning MongoDB or developing small
proof -of- concept applications.

Step 4: Select your preferred Cloud Provider & Region. It supports M0 Free Tier clusters on Amazon Web
Services (AWS), Google Cloud Platform (GCP), and Microsoft Azure. The regions that support M0 Free tier
clusters are marked with the "Free Tier Available" label.

Step 5: Select M0 Sandbox for cluster tier: Selecting M0 automatically locks the remaining configuration
options. If you can't select the M0 cluster tier, return to the previous step and choose a Cloud Provider &
Region that supports M0 Free Tier clusters.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

43 UNIT-4 MSD

Step 6: Enter a name for your cluster in the Cluster Name field; you can enter any name for your cluster.
The cluster name contains ASCII letters, numbers, and hyphens.

Step 7: Click on Create Cluster to deploy the cluster. Once you deploy your cluster, it can take up to 5-10
min for your cluster to provision and become ready to use.

Step 8: Once we register, Atlas automatically creates a default organization and project where we can deploy our first
cluster. We can add additional organizations and projects later.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

44 UNIT-4 MSD

MongoDB Compass:(install and configure )


MongoDB Compass is a GUI for MongoDB. It is also known as MongoDB GUI.
MongoDB allows users to analyze the content of their stored data without any prior knowledge of
MongoDB query syntax. When we explore exploring our data in the visual environment, we can use
Compass GUI to optimize performance, manage indexes, and implement document-validation.

All the versions of MongoDB Compass are opensource (i.e., we can freely deploy and view the repositories
of all MongoDB GUI versions). The source repositories of MongoDB compass can be found on the
following link of GitHub

https://github.com/mongodb-js/compass/

Available Compass Edition


MongoDB GUI is available in the following four editions:

o Compass Community: This edition is designed for developing with MongoDB and includes a subset of the
features of Compass.
o Compass: It is released as the full version of MongoDB Compass. It includes all the features and capabilities
that MongoDB provides.
o Compass Randomly: It is limited to read operation only with all update and delete capabilities removed.
o Compass Isolated: The Isolated edition of MongoDB compass doesn't start any network requests except to the
MongoDB server to which MongoDB GUI connects. It is designed to use in highly secure environments.

How to Download and Install MongoDB Compass


Step 1: To download MongoDB Compass, you can use your preferred web browser, and Open
the https://www.mongodb.com/download-center/compass?jmp=docs page.

Step 2: You need to select the installer and version you prefer. GUI installer are available as a .exe or .msi
package or a .zip archive.

Step 3: Finally, Click on the download button.

Step 4: Click on the installer file after the download is complete.

Step 5: Follow the pop-ups to install MongoDB Compass GUI.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

45 UNIT-4 MSD

Step 6: Once it is installed, it launches and ask you to configure privacy settings and specify update
preference.

Introduction to MongoDB Shell:


MongoDB have a JavaScript shell that allows interaction with MongoDB instance from the command line.

If you want to create a table, you should name the table and define its column and each column's data type.

The shell is useful for performing administrative functions and running instances.

How to run the shell


To start the shell, open command prompt, run it as a administrator then run the mongo executable:

1. $ mongo

MongoDB shell version: 2.4.0


Connecting to: test

You should start mongoDB before starting the shell because shell automatically attempt to connect to a
MongoDB server on startup.

The shell is a full-featured JavaScript interpreter. It is capable of running Arbitrary JavaScript program.

Let us take a simple mathematical program:

1. >x= 100
2. 100
3. >x/ 5;
4. 20

You can also use the JavaScript libraries

1. > "Hello, World!".replace("World", "MongoDB");

Hello, MongoDB!

You can even define and call JavaScript functions

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

46 UNIT-4 MSD

1. > function factorial (n) {


2.
3. ... if (n <= 1) return 1;
4.
5. ... return n * factorial(n - 1);
6. ... }
7.
8. > factorial (5);
9.
10. 120

When you press "Enter", the shell detect whether the JavaScript statement is complete or not.

If the statement is not completed, the shell allows you to continue writing it on the next line. If you press
"Enter" three times in a row, it will cancel the half-formed command and get you back to the > - prompt.

Introduction to mongo db data types:


MongoDB supports many datatypes. Some of them are −
 String − This is the most commonly used datatype to store the data. String in MongoDB
must be UTF-8 valid.
 Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon your server.
 Boolean − This type is used to store a boolean (true/ false) value.
 Double − This type is used to store floating point values.
 Min/ Max keys − This type is used to compare a value against the lowest and highest
BSON elements.
 Arrays − This type is used to store arrays or list or multiple values into one key.
 Timestamp − ctimestamp. This can be handy for recording when a document has been
modified or added.
 Object − This datatype is used for embedded documents.
 Null − This type is used to store a Null value.
 Symbol − This datatype is used identically to a string; however, it's generally reserved for
languages that use a specific symbol type.
 Date − This datatype is used to store the current date or time in UNIX time format. You can
specify your own date time by creating object of Date and passing day, month, year into it.
 Object ID − This datatype is used to store the document’s ID.
 Binary data − This datatype is used to store binary data.
 Code − This datatype is used to store JavaScript code into the document.
 Regular expression − This datatype is used to store regular expression.

Mongo DB CRUD Operations:

CRUD operations create, read, update, and delete documents.

Create Operations

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

47 UNIT-4 MSD

Create or insert operations add new documents to a collection. If the collection does not currently
exist, insert operations will create the collection.

MongoDB provides the following methods to insert documents into a collection:

 db.collection.insertOne() New in version 3.2

 db.collection.insertMany() New in version 3.2

In MongoDB, insert operations target a single collection. All write operations in MongoDB
are atomic on the level of a single document.

Read Operations

Read operations retrieve documents from a collection; i.e. query a collection for documents.
MongoDB provides the following methods to read documents from a collection:

 db.collection.find()

You can specify query filters or criteria that identify the documents to return.

Update Operations

Update operations modify existing documents in a collection. MongoDB provides the following
methods to update documents of a collection:

 db.collection.updateOne() New in version 3.2

 db.collection.updateMany() New in version 3.2

 db.collection.replaceOne() New in version 3.2

In MongoDB, update 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 update. These filters use the
same syntax as read operations.

Delete Operations

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

48 UNIT-4 MSD

Delete operations remove documents from a collection. MongoDB provides the following methods
to delete documents of a collection:

 db.collection.deleteOne() New in version 3.2

 db.collection.deleteMany() New in version 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.

Creat and delete databases and collections:


MongoDB has no "create" command for creating a database. Also, it is essential to note that
MongoDB does not provide any specific command for creating a database. This might seem a bit
agitated if you are new to this subject and database tool or in case you have used that
conventional SQL as your database where you are required to create a new database, which will
contain table and, you will then have to use the INSERT INTO TABLE to insert values manually
within your table.

In this MongoDB tool, you need not have to produce, or it is optional to create a database
manually. This is because MongoDB has the feature of automatically creating it for the first time
for you, once you save your value in that collection. So, explicitly, you do not need to mention or
put a command to create a database; instead it will be created automatically once the collection is
filled with values.

You can make use of the "use" command followed by the database_name for creating a database.
This command will tell the MongoDB client to create a database by this name if there is no
database exists by this name. Otherwise, this command will return the existing database that has
the name.

Syntax:

use my_project_db

Here 'use' is the command for creating a new database in MongoDB and 'my_project_db' is the name of the database.
This will prompt you with a message that it has switched to a new DB (database) name 'my_project_db'.

DELETING A DATABASE IN MONODB:

if you are familiar with SQL, then you must have heard about the drop
command. The concept of drop in SQL is used to delete the entire database or just the table, i.e.,
it destroys the objects like an existing database. In MongoDB, the dropDatabase command is
implemented for a similar purpose. This also helps in deleting the connected data files of that
database. For operating this command, you have to reside on the current database.

Example:

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

49 UNIT-4 MSD

db.dropDatabase()
{ "dropped": "my_project_db", "ok":

EXAMPLE:

Create, Delete Database and Collection:


(1) Change active Database
use <database name>
(2) Create new Collection
db.createCollection("<collection name>")
(3) List all Collections inside active Database
show collections
(4) Delete Collection
db.getCollection("<collection name>").drop()
db.<collection name>.drop()
(5) Delete Database
db.dropDatabase()

INTRODUCTION TO MongoDB Queries:

MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries
provide the simplicity in process of fetching data from the database, it’s similar to SQL
queries in SQL Database language. While performing a query operation, one can also
use criteria or conditions which can be used to retrieve specific data from the database.
MongoDB provides the function names as db.collection_name.find() to operate query
operation on database. In this post, we discussed this function in many ways using
different methods and operators.
Here, we are working with:
Database: geeksforgeeks
Collection: Article

Note: Here “pretty()” query method is using for only better readability of Document
Database.(It’s not necessary)

Field selection

The find() method displays the database collection in Non-Structured form({<Key> :


<value>}) including auto-created <key> ” id ” by MongoDB and collection data inserted
by user or admin.
Syntax:

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

50 UNIT-4 MSD

db.collection_name.find()
Example:
db.article.find()
This method is used to display all the documents present in the article collection.

Finding a single document

In MongoDB, we can find a single document using findOne() method, This method
returns the first document that matches the given filter query expression.
Syntax:
db.collection_name.findOne ()
Example:
db.article.findOne()
Here, we are going to display the first document of the article collection.

Displaying documents in a formatted way

In MongoDB, we can display documents of the specified collection in well-formatted way


using pretty() method.
Syntax:
db.collection_name.find().pretty()
Example:
db.article.find().pretty()
Here, we are going to display the documents of the article collection in a well-formatted
way using pretty() method.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)


lOMoARcPSD|34807602

51 UNIT-4 MSD

Equal filter query

The equality operator($eq) is used to match the documents where the value of the field is
equal to the specified value. In other words, the $eq operator is used to specify the
equality condition.
Syntax:
db.collection_name.find({< key > : {$eq : < value >}})
Example:
db.article.find({author:{$eq:"devil"}}).pretty()
Here, we are going to display the documents that matches the filter
query(i.e., {author : {$eq : “devil”}}) from the article collection.

Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy