Studocu Unit-4
Studocu Unit-4
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).
2 UNIT-4 MSD
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.
Installing TypeScript:
3 UNIT-4 MSD
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.
pm/
In the same Node.js command prompt, type the "npm i –g typescript" command to
download the TypeScript module from the repository.
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:
4 UNIT-4 MSD
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.
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.
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:
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.
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.
8 UNIT-4 MSD
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:
9 UNIT-4 MSD
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
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.
In a shopping cart application, you can use the arrow function to perform filtering,
sorting, searching operations, and so on.
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.
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.
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.
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.
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.
What is an Interface?:
An interface in TypeScript is used to define contracts within the code.
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
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.
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.
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.
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
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.
18 UNIT-4 MSD
Access Modifiers:
Access modifiers are used to provide certain restriction of accessing the properties and
methods outside the class.
19 UNIT-4 MSD
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.
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.
21 UNIT-4 MSD
What is a Namespace?
A Namespace is used to group functions, classes, or interfaces under a common name.
22 UNIT-4 MSD
To import the namespace and use it, make use of the triple slash reference tag.
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.
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.
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.
To compile the modules and the file which is using the module, compile them together
using the tsc command.
26 UNIT-4 MSD
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.
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.
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.
Consider the below code where you implement a similar function for two different types
of data:
28 UNIT-4 MSD
Avoid writing the same code again for different types using generics. Let us rewrite the
above code using generics:
The actual type will be provided while invoking function or instance creation.
To access this function with different types you will use the below code:
Generic Functions:
Generic functions are functions declared with generic types.
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.
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
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.
To invoke this generic function, you can pass any parameter which has a length
property.
31 UNIT-4 MSD
PART-B
…………………………………………………………………………………………………………………………………………………….
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.
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.
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.
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.
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
FirstName = "John",
Address = "Detroit",
Spouse = [{Name: "Angela"}].
FirstName ="John",
33 UNIT-4 MSD
Address = "Wick"
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:
In MongoDB, you can search by field, range query and it also supports regular expression searches.
2. Indexing
3. 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
10. Stores files of any size easily without complicating your stack.
Document Database
Downloaded by karibugatha yaswanth (ykaribugatha@gmail.com)
lOMoARcPSD|34807602
34 UNIT-4 MSD
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.
JSON Format
{
"name1": value1,
"name2": value2,
"name3": value3,
.
.
.
"nameN": valueN
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"
}
]
}
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
}
37 UNIT-4 MSD
38 UNIT-4 MSD
39 UNIT-4 MSD
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.
md\data\db
For example:
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:
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:
If you have spaces in your path, enclose the entire path in double space.
For example:
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.
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.
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.
Step 2: When you click on Start Free, you will be redirected to the Registration form for an account on the
MongoDB Atlas.
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.
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.
44 UNIT-4 MSD
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/
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.
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.
45 UNIT-4 MSD
Step 6: Once it is installed, it launches and ask you to configure privacy settings and specify update
preference.
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.
1. $ mongo
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.
1. >x= 100
2. 100
3. >x/ 5;
4. 20
Hello, MongoDB!
46 UNIT-4 MSD
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.
Create Operations
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.
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:
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
48 UNIT-4 MSD
Delete operations remove documents from a collection. MongoDB provides the following methods
to delete documents of a collection:
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.
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'.
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:
49 UNIT-4 MSD
db.dropDatabase()
{ "dropped": "my_project_db", "ok":
EXAMPLE:
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
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.
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.
51 UNIT-4 MSD
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.