0% found this document useful (0 votes)
13 views69 pages

MongoDB Overview and Benefits

MongoDB is a NoSQL, document-oriented database management system that stores data in key-value pairs and is known for its high availability, performance, and scalability. It allows for dynamic schemas and is widely used by various organizations for managing big data and diverse applications. The document outlines key concepts, advantages, and installation instructions for MongoDB, highlighting its flexibility compared to traditional relational databases.

Uploaded by

kachariyaaadarsh
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)
13 views69 pages

MongoDB Overview and Benefits

MongoDB is a NoSQL, document-oriented database management system that stores data in key-value pairs and is known for its high availability, performance, and scalability. It allows for dynamic schemas and is widely used by various organizations for managing big data and diverse applications. The document outlines key concepts, advantages, and installation instructions for MongoDB, highlighting its flexibility compared to traditional relational databases.

Uploaded by

kachariyaaadarsh
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

Overview of MongoDB

MongoDB - Overview
Like any other database management language, MongoDB is based on a NoSQL
database that is used for storing data in a key-value pair. Its working is based on the
concept of document and collection. It is also an open-source, a document-oriented,
cross-platform database system that is written using C++. In this chapter, you will learn
more about MongoDB and its importance.

Mongo DB can be defined as a document-oriented database system that uses the


concept of NoSQL. It also provides high availability, high performance, along with
automatic scaling. This open-source product was developed by the company - 10gen in
October 2007, and the company also maintains it. MongoDB exists under the General
Public License (GPL) as a free database management tool as well as available under
Commercial license as of the manufacturer. MongoDB was also intended to function
with commodity servers. Companies of different sizes all over the world across all
industries are using MongoDB as their database.

Here are some key terminologies that you must know to get into the in-depth of
MongoDB:

What is a Database?
In MongoDB, a database can be defined as a physical container for collections of data.
Here, on the file system, every database has its collection of files residing. Usually, a
MongoDB server contains numerous databases.

What are Collections?


Collections can be defined as a cluster of MongoDB documents that exist within a
single database. You can relate this to that of a table in a relational database
management system. MongoDB collections do not implement the concept of schema.
Documents that have collection usually contain different fields. Typically, all the
documents residing within a collection are meant for a comparable or related purpose.

What is a Document?
A document can be defined as a collection of key-value pairs that contain dynamic
Overview of MongoDB

schema. Dynamic schema is something that documents of the equal collection do not
require for having the same collection of fields or construction, and a common field is
capable of holdingvarious types of data.

Here is a table showing the relation between the terminologies used in RDBMS and
MongoDB:

RDBMS MongoDB

Database Database

Table Collection

Tuple or Row Document

Column Field

Table Join Embedded Documents

Primary Key Primary key / Default key

Mysqld / Oracle mongod

Popular Organizations That Use MongoDB


Here is a list of some popular and multinational companies and organizations that are
using MongoDB as their official database to perform and manage different business
applications.

● Adobe
● McAfee
● LinkedIn
● FourSquare
● MetLife
● eBay
Overview of MongoDB

● SAP

Where Is MongoDB Used?


Beginners need to know the purpose and requirement of why to use MongoDB or what
is the need of it in contrast to SQL and other database systems. In simple words, it can
be said that every modern-day application involves the concept of big data, analyzing
different forms of data, fast features improvement in handling data, deployment
flexibility, which old database systems are not competent enough to handle. Hence,
MongoDB is the next choice.

Why Use MongoDB?


Some basic requirements are supported by this NoSQL database, which is lacking in
other database systems. These collective reasons make MongoDB popular among
other databasesystems:

● Document-Oriented data storage, i.e., data, is stored in a JSON style format,


which increases the readability of data as well.
● Replication and high availability of data.
● MongoDB provides Auto-sharding.
● Ad hoc queries are supported by MongoDB, which helps in searching by range
queries,field, or using regex terms.
● Indexing of values can be used to create and improve the overall search
performance in MongoDB. MongoDB allows any field to be indexed within a
document.
● MongoDB has a rich collection of queries.
● Updating of data can be done at a faster pace.
● It can be integrated with other popular programming languages also to handle
structured as well as unstructured data within various types of applications.

Advantages of Using MongoDB


● It is easy to set up, i.e., install the MongoDB.
● Since MongoDB is a schema-less database, so there is no hassle of schema
migration.
● Since it is a document-oriented language, document queries are used, which
Overview of MongoDB

plays avital role in supporting dynamic queries.


● Easily scalable.
● It is easy to have a performance tuning as compared to other relational databases.
● It helps in providing fast accessing of data because of its nature of
implementing the internal memory to store the data.
● MongoDB is also used as a file system that can help in easy management
of loadbalancing.
● MongoDB also supports the searching using the concept of regex (regular
expression)as well as fields.
● Users can run MongoDB as a windows service also.
● It does not require any VM to run on different platforms.
● It also supports sharding of data.

Some Common Questions Related to MongoDB

Q. Does a MongoDB database have schemas?


Yes, MongoDB makes use of schemas, which are dynamic schemas. In such
types of
schemas, you can modify the construction of documents by merely
accumulating new fields as well as delete existing ones.

Q. Does MongoDB provide SQL support?

No, MongoDB does not provide SQL support.

Q. What are the various areas where MongoDB can be used?

MongoDB can be used in supporting content management systems, online and


offline gaming applications, e-commerce systems, mobile applications, data
analytics section,archiving, as well as logging.
MongoDB - Benefits of Using NoSQL

MongoDB - Introduction to NoSQL


Like another database scripting/query languages such as SQL, MySQL, and Oracle,
MongoDB also provides a high performance, scalability as well as availability for
managing the database. MongoDB is one of the most accepted NoSQL database and
stores data in a JSON structure. It is what makes Mongo DB so scalable as well as
flexible. In this chapter, you will learn about the concept of NoSQL and its types and
benefits.

What is NoSQL Database?


NoSQL can be defined as a database which is employed for managing the massive
collection of unstructured data and when your data is not piled up in a tabular format or
relations like that of relational databases. The term NoSQL came from the word non SQL
or nonrelational. There are a wide variety of existing Relational Databases that have
been unsuccessful in solving several complex modern problems such as:

● A dynamic change in the nature of data - i.e., nowadays data are in structured,
semi-structured, nonstructured as well as polymorphic in type.
● The variety of applications and the type of data feed into them for analysis
has now become more diverse and distributed and is approaching cloud-
oriented.
● Also, modern applications and services are serving tens of thousands of users in
diverse geo-locations, having diverse time zones. So data integrity needs to be
there at all the time.

Data residing in multiple virtual servers and other cloud storage (remote-based) in the
cloud infrastructure can be easily analyzed using the NoSQL database management
techniques and largely when the data set is in a non-structured manner. So, it can be
said that the NoSQL database is intended to overcome the diversity of data, increase
performance, modeling of data, scalability, and distribution, which is usually
encountered in the Relational Databases.
MongoDB - Benefits of Using NoSQL

Structured Data Vs. Unstructured Data


Structured data are in a proper format, usually text files or which can be represented
in a tabular format. Also, such types of data can be smoothly represented in chart-like
form, and data mining tools can be used to process them efficiently.

Whereas unstructured data are haphazard data formats (such as document files,
image files, video files, icons, etc.) where structured data can be pulled out or mine
from unstructured data, but this process usually takes a lot of time. Modern-day data
generated from different applications, services, or sources are a combination of
structured and unstructured both. So, you will need something to store such data to
make your application work properly. NoSQL based languages and scripts can help
in this regard.

Types of Database in NoSQL


Here are some of the common database types that come under NoSQL:

1. Document type databases: Here, the key gets paired with a compound data
structure, i.e., document. MongoDB is an example of such type.
2. Key-Value stores: Here, each unstructured data is stored with a key for recognizing
it.
3. Graph stores: In this type of database, data is stored mostly for networked data. It
helps to relate data based on some existing data.
. Wide-column stores: This type of data stores large data sets Cassandra (Used by
Facebook), HBase are examples of such type.

Benefits of NoSQL Type Database


● It allows developers to create large volumes of structured, semi-structured as
well as unstructured data for making the application diverse and not restricting
its use becauseof the type of data being used within the application.
● It also allows agile development; rapid iteration along with frequent code pushes,
whichmakes it more popular.
● It can be used with object-oriented programming (OOP), which makes it easy to
use with flexibility.
● Data can be stored more efficiently, making it less expensive, providing
massivearchitecture.
MongoDB - Benefits of Using NoSQL

MongoDB - Benefits of Using NoSQL


NoSQL can be defined as a technique for database design, which helps accommodate a
wide range of data models, including key-value, columnar, documents, or graph data.
NoSQL is abbreviated as "not only SQL" is introduced to act as an alternative for
traditional relational databases. In this chapter, you will learn about the various benefits
that NoSQL has over other traditional database management systems.

Benefits of Using NoSQL


1. High elastic Scalability: In the case of traditional database services, there is a
limitation where DBAs have to rely on scaling according to the development
requirement. It ultimately intends for database users or organizations to purchase
larger servers to cope with the increasing data load. In those scenarios, NoSQL
databases put forward a much easier alternative of scaling out - the database gets
distributed transversely numerous pre-existing hosts. As the demand for data
storage availability is increasing, scaling out as a virtual environment will offer an
added economical alternative for hardware scaling. It is a challenge to scale
RDBMS data to commodity servers as cluster servers, which can be easily
controlled using NoSQL databases, as they are pre-programmed to achieve scale
on new nodes. These hardware costs are also low, which makes data storage
affordable.

2. Valuable and reliable for big data: Each organization, application, and services are
generating large amounts of data that need to be stored appropriately. It brings
into focus the concept of 'big data,' which focuses on the "industrial revolution of
data". Usually, this is not possible for RDBMS; it is not able to store unstructured
data and different types and vast amounts of data. This is why organizations
turned towards using NoSQL systems such as MongoDB or Hadoop to handle 'big
data' volumes.

3. Reduced dependence/trust in in-house DBAs: The most crucial drawback of


employing powerful high-end RDBMSs is maintenance, which can probably be
done by employing trained DBAs, and they have higher pay scales. DBAs
(Database Administrators) are implicated in designing, installing as well as
performing these RDBMS operations, making it virtually indispensable. But in the
MongoDB - Benefits of Using NoSQL

case of NoSQL databases, they are intended for less hands-on administration,
having features like data distribution, simplified data models, auto management
and fetching data using simple code, and auto-repairing of data. So,

management and organizing of data can be done remotely also by remote-DBAs,


which is less costly and more straightforward.

4. It's cheaper: NoSQL databases are intended for utilizing inexpensive commodity
hardware for constructing clusters of the server, which helps in managing huge
data volumes and transaction of data. On the other hand, traditional RDBMSs
systems want expensive storage and original servers; this means they pose a
higher cost per volumes for storing the data.

5. Agile data models: Traditional database systems usually give immense headaches
for managing the changes in storage and operational architecture, particularly for
the large production ones. In such a system, minor changes need to be monitored
carefully. On the other hand, NoSQL database systems do not contain such
limitations on their data- storage models. They are flexible for any type of
changes in not only the genre of data but also the architecture of data-storage,
allowing comparative agility like the addition of new columns with no significant
alterations or breakdown.
6/4/22, 10:14 AM History of MongoDB

MongoDB - History
Since you are now familiar with the various features of MongoDB, and its
characteristics and how it is related to NoSQL, it is time to know the history of
MongoDB. In this chapter, you willbriefly learn the history of MongoDB.

The development of MongoDB was started in early 2007 when the company was
developing a Microsoft Azure-like platform as a service. This was a New York based
company name 10gen which is now changed its name to MongoDB Inc. The initial
development was focused on building a PaaS (Platform as a Service), but later in 2009,
MongoDB came to the market as an open-source database server and was maintained
by this organization itself.

In the year March 2010, it launched its first ready product which was version 1.4. The
latest, as well as the stable version of MongoDB, is version 2.4.9 that was released on
Jan 10, 2014.
MongoDB - Environment Setup

MongoDB - Environment Setup

Install MongoDB Server, MongoDB Shell, Compass on Windows


Here you will learn how to install MongoDB server, MongoDB Shell, and compass on
your local Windows machine.
Visit [Link] to download the MongoDB installer for your required
platform.

MongoDB Official Website


Here, we are going to install a free MongoDB database server on our local Windows
machine. So, click on the Product menu -> Community Server, as shown below.
MongoDB - Environment Setup

MongoDB Community Edition

This will open a download page where you can select the version, platform, and
package options.

5.8M
Elon Musk Faces SEC Investigation and Lawsuit by Twitter Investors for Delayed
Disclosure
Here, we will download the latest version of MongoDB, Windows platform, and msi file
as a package, as shown below.

Download MongoDB
Click on the Download button to download the installer file.
MongoDB - Environment Setup

Once fully downloaded, click on the msi file to start the installation wizard, as shown
below.

MongoDB Installation Wizard


Click Next to start the installation.

MongoDB Installation Wizard


MongoDB - Environment Setup

Check the "I accept the terms in the License Agreement" checkbox and click Next.

MongoDB Installation Wizard


Here, you will have two options for installation: Complete and Custom. The complete
option will install all the features. The custom option allows you to select only required
features.
You can select either of these two options. Here, we will select the custom option just
to show you what all things it will install. So, click on the Custom option which will take
you to the next step, as shown below.

MongoDB Installation Wizard


MongoDB - Environment Setup

In the custom setup page, expand the MongoDB node to see what all features will be
installed. It will install Server, Client, Router, and Miscellaneous Tools for the MongoDB
database. It also displays the location where the MongoDB is going to be installed. You
may change it or keep the default location and click Next.
Click Next to configure the MongoDB service, as shown below.

Configure MongoDB Service

MongoDB server will be installed as a service on your local Windows machine. As you
can see above, you have an option to run a service as Network Service user or as a
local or domain user. We will select "Run service as Network Service User" radio
button.

You may change the default service name but it is recommended to keep the default
"MongoDB" name to identify it easily.

MongoDB database stores the data as BSON files on your local machine. You can
change the default location where the data files and log files are going to be stored.
Here, we will keep the default paths and click the Next button.

On the next page, select "Install MongoDB Compass" checkbox and click Next.
MongoDB - Environment Setup

MongoDB Compass is a GUI tool for MongoDB database where you can visually explore
data, run queries, and optimize performance.

MongoDB Compass Installation


Next, click on the Install button to start the installation.

MongoDB Installation
It will take a few minutes to install. Once installed succefully, click on the Finish button
to close the wizard.
MongoDB - Environment Setup

MongoDB Installation
It will also open MongoDB Compass, as shown below.

MongoDB Compass
MongoDB - Environment Setup

MongoDB Server
We installed MongoDB as a Network service. To see this, open Services by searching
"service" in the windows search box and click on the Services app, as shown below.

MongoDB Service
On the Services window, navigate to MongoDB Server, as shown below. You will find
that it is already up and running.

MongoDB Service on Windows


Now, the MongoDB Server service is already running, you can connect the MongoDB
MongoDB - Environment Setup

client to connect with this MongoDB server and execute the commands.

MongoDB Client
MongoDB clients can be your application, MongoDB Shell, MongoDB Compass, or
anything which wants to connect and store data to the MongoDB server.
Here, we already installed two clients, MongoDB Shell and MongoDB Compass.

Go to the path where MongoDB was installed. By default it is "C:\Program


Files\MongoDB\Server\5.0\bin", as shown below.

MongoDB Installation Folder


Here, you will find [Link], which is MongoDB Shell. Click on [Link] to start
the client, as shown below.

MongoDB Shell
You can execute the commands here. For example, write "show dbs" and press Enter
MongoDB - Environment Setup

to display the database it already has, as shown below.

MongoDB Shell Command

Thus, you can install the MongoDB server, clients (MongoDB Shell and Compass), and
other features.

MongoDB Shell
MongoDB Shell is the quickest way to connect, configure, query, and work with your
MongoDB database. It acts as a command-line client of the MongoDB server.
The MongoDB Shell is a standalone, open-source product and developed separately
from the MongoDB Server under the Apache 2 license. It is a fully functional JavaScript
and [Link] 14.x REPL for interacting with MongoDB servers.
MongoDB Shell is already installed with MongoDB. You can find it in the installation
directory where you installed MongoDB. By default, it is "C:\Program
Files\MongoDB\Server". Open the installation folder and appropriate version folder and
go to the "bin" folder. Here, "[Link]" is MongoDB shell. Click on it to open the
MongoDB shell, as shown below.
MongoDB - Environment Setup

MongoDB Shell
New MongoDB Shell - mongosh
In the installation folder, if you find [Link] instead of [Link] then you
already have a new MongoDB shell. If you don't find it, then you need to install it
separately.
The new MongoDB Shell mongosh has some more features than old shell mongo such
as intelligent autocomplete and syntax highlighting, easy to understand error
messages, formatting feature to present the output in a readable format, etc.
However, all the commands will be executed in mongosh as well as mongo shell.
Install mongosh

To install the new MongoDB shell (mongosh), visit [Link] and click on
Product menu -> Tools -> Database Shell, as shown below.
MongoDB - Environment Setup

Download New MongoDB Shell

On the MongoDB Shell page, click on the Download button to download the shell.

Download New MongoDB Shell


This will take you to a page where you can select a version, platform, and package to
download, as shown below.
MongoDB - Environment Setup

Download New MongoDB Shell

Click on the Download button to download the installer file.


Now, click on the downloaded installer file to start the installation wizard, as shown
below.

Install New MongoDB Shell - mongosh

Click Next to go to next step shown below.


MongoDB - Environment Setup

Install New MongoDB Shell - mongosh


Here, uncheck the checkbox if you want to install shell for all users on your local
machine and click Next.

Install New MongoDB Shell - mongosh


Click on the Install button to start the installation. It should quickly install it.
MongoDB - Environment Setup

Install New MongoDB Shell - mongosh

Once installation completes, click the Finish button to close the wizard.

This should have installed mongosh in "C:\Program Files\mongosh" folder on Windows,


as shown below.

New MongoDB Shell - mongosh


Click on the [Link] to open a new MongoDB shell, as shown below.
MongoDB - Environment Setup

New MongoDB Shell - mongosh


Press Enter to start the shell, as shown below.

New MongoDB Shell - mongosh


Alternatively, open a new command prompt on Windows and write mongosh and press
Enter. It will open the same MongoDB shell.
Execute MongoDB Commands

You can execute MongoB commands for CRUD operations on MongoDB shell (mongo or
mongosh). For example, execute the "shows dbs" command to see all the databases
on the connected MongoDB server.
> show dbs
MongoDB - Environment Setup

admin 41 kB
config 111 kB
local 41 kB

Use the "db" command to check the current database.


> db
test
Run the .editor command to execute multi-line commands. Press Ctrl + d to run a
command or Ctrl + c to cancel.
MongoDB shell is JavaScript and [Link] REPL, so you can also execute limited
JavaScript code.
> "Hello".length
5

Press Ctrl + c twice to exit from the MongoDB shell.

MongoDB Compass
MongoDB Compass is a GUI based tools (unline MongoDB Shell) to interact with local
or remote MongoDB server and databases. Use Compass to visually explore your data,
run ad hoc queries, perform CRUD operations, and view and optimize your query
performance. It can be installed on Linux, Mac, or Windows.
If you have not installed MongoDB Compass with the MongoDB, then download the
free community version of Compass for your platform from here.
Now, do a window search on "mongodb compass" and open it, as shown below.

MongoDB Compass
MongoDB - Environment Setup

On the main page, click on the New Connection tab on the left pane to open New
Connection page shown above. You can paste a connection string or click on Fill in
connection fields individually link. This will open the following window where you can
enter the host name, port, username, password, etc.

MongoDB Compass
This already has default parameters, just click OK to connect with your local server, as
shown below.

MongoDB Compass
As you can see above, it will display all the databases on the connected MongoDB
server. On the left pane, it displays information about the connected server.
Now, you can create, modify, delete databases, collections, documents using MongoDB
MongoDB - Environment Setup

Compass. Click on the CREATE DATABASE button to create a new database. This will
open Create Database popup, as shown below.

MongoDB Compass - Create Database


Enter your database name and collection name and click Create Database. This will
create a new database humanResourceDB with the new employees collection shown
below.

MongoDB Compass - Collections


Click on employees collection to insert, update, find documents in it. This will open the
following window to manage documents.
MongoDB - Environment Setup

MongoDB Compass - Manage Documents

Thus, you can use MongoDB Compass UI to manage your MongoDB databases.
Database Create and Drop in MongoDB

MongoDB - Database Create and Drop


For storing data in a MongoDB, you need to create a database first. It will allow you to
systematically organize your data so that it can be retrieved as per requirement. If you
wish to delete a database, MongoDB also allows you to delete that. In this chapter, you
will learn how to create and delete a database in MongoDB.

Concept of Creating a Database in MongoDB


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 oncethe collection is filled with values.

The "use" Command for Creating Database in MongoDB


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 existingdatabase that has the name.

Syntax:

use my_project_db

Example:
6/4/22, 10:17 AM Create Collection in MongoDB

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

View the List of Databases in MongoDB


If you are eager to check the list of database that is residing with MongoDB, you can
use the show dbs command. By default, it may not show your created database, and
MongoDB's default database is a test.

show dbs

In order to make a list show your database name, you have to make use of the command:

Example:

[Link]({"name":"Avengers: Endgame"})

Now, when you again use the show dbs command, it will now show your created
database name in the list.

It is to be noted that, for checking your currently selected database, you can
use the command:

db
6/4/22, 10:17 AM Create Collection in MongoDB

Deleting a Database in MongoDB

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:
[Link]()
{ "dropped": "my_project_db", "ok": 1}

This will drop the existing database in which you are residing and will show the above
message.
6/4/22, 10:17 AM Create Collection in MongoDB

MongoDB - Data Types


Data type is an essential component of a language or script that is used to define the
type of data being used in framing the database. It is important for you to know that
MongoDB stores data in BSON format. In this chapter, you will learn about the different
data types that exist in MongoDB, along with their implementation techniques.

What Are JSON and BSON?


JSON based databases usually return query results which can be effortlessly parsed,
having modest or nix transformation, straightforwardly by the use of JavaScript along
with most well-liked programming languages - dropping the quantity of logic one needs
for building your application layer.

In the case of MongoDB, data representation is done in JSON document format, but
here the JSON is binary-encoded, which is termed as BSON. BSON is the extended
version of the JSON model, which is providing additional data types, makes
performance to be competent to encode and decode in diverse languages and ordered
fields.

Different MongoDB Data Types


Remote procedure calls in MongoDB can be made by using the BSON format. MongoDB
has a unique way of representing data types in which each data type is associated with
an alias as well as a number that is usually used to search or find any specific record
within a MongoDB database. MongoDB allows its users to implement different variations
of data types:

Integer
Integer is a data type that is used for storing a numerical value, i.e., integers as you
can save in other programming languages. 32 bit or 64-bit integers are supported,
which depends on the server.

Example:
[Link]({"Integer example": 62})
6/4/22, 10:17 AM Create Collection in MongoDB

Output:

Boolean
Boolean is implemented for storing a Boolean (i.e., true or false) values.

Example:

[Link]({"Nationality Indian": true})

Output::

Double
Double is implemented for storing floating-point data in MongoDB.

Example:

[Link]({"double data type": 3.1415})

Output:
6/4/22, 10:17 AM Create Collection in MongoDB

Min/Max keys
Min / Max keys are implemented for comparing a value adjacent to the lowest as
well ashighest BSON elements.

String
String is one of the most frequently implemented data type for storing the data.

Example:

[Link]({"string data type" : "This is a sample message."})

Output:

Arrays
Arrays are implemented for storing arrays or list type or several values under a single key.

Example:

var degrees = ["BCA", "BS", "MCA"]


[Link]({" Array Example" : " Here is an example of arra
y",
" Qualification" : degrees})

Output:
6/4/22, 10:17 AM Create Collection in MongoDB

Object
Object is implemented for embedded documents.

Example:

var embeddedObject={"English" : 94, "ComputerSc." : 96, "Maths" : 80,


"GeneralSc." : 85}

[Link]({"Object data type" : "This is Object",


"Marks" : embeddedObject})

Output:

Symbol
Symbol is implemented to a string and is usually kept reticent for languages having
specific symbol type.

Null
Null is implemented for storing a Null value.

Example:
6/4/22, 10:17 AM Create Collection in MongoDB

[Link]({" EmailID ": null})

Output:

Date
Date is implemented for storing the current date and time as UNIX-time format.

Example:

var date=new Date()


var date2=ISODate()

var month=[Link]()
[Link]({"Date":date, "Date2":date2,"Month":month})

Output:

Timestamp
Timestamp stores 64-bit value, in which the first 32 bits are time_t value (seconds epoch)
and the other 32 bits are ordinal to operate within a given second.

Binary data
Binary data is implemented for storing binary data.
6/4/22, 10:17 AM Create Collection in MongoDB

Object ID
Object ID is implemented for storing the ID of the document.

Regular expression
Regular expression is implemented for storing regular expression.

Code
Code is implemented for storing JavaScript code for your MongoDB

document. In the next chapters, all data types and uses have been

explained more deeply.


6/4/22, 10:17 AM Create Collection in MongoDB

MongoDB - Create Collection


Collections are like that of tables of RDBMS and are capable enough to store
documents of diverse or dissimilar types. Creation and removal of collections in
MongoDB can be done in specific ways. In this chapter, you will learn about the
creation of collections in a database created using MongoDB.

Creating a Collection in MongoDB


Creation of collection can be done using [Link](name, options). But,
typically you will not require building or constructing a collection of your own.
MongoDB does this creation task automatically as you start to insert some documents
for making a database.
Here is a syntax that will tell you how to create your collection in MongoDB:

Syntax:

[Link](collection_name, options)

Here, [Link]() is the method used; "name" is a data type - string which
is specifying the name of the collection to be formed. "options" is an added document
type which helps in specifying the size of memory along with indexing the collection in
the database. This parameter is an optional one.

The following example shows the syntax of the createCollection() method with its options:

Example:

[Link](<collection_name>, { capped: <boolean>,


autoIndexId:
<boolean>,size:
<number>,
max: <number>,
storageEngine:
<document>, validator:
<document>,
validationLevel:
<string>,
6/4/22, 10:17 AM Create Collection in MongoDB

validationAction:
<string>,
indexOptionDefaults: <document>,
viewOn: <string>,
pipeline: <pipeline>,
collation: <document>,
writeConcern: <document>} )

Here is the detailing of some important fields that can be used as options in the
createcreateCollection() method:

Field for
Type Description
option

capped Boolean Capped collection is a predetermined size of the


collection which gets automatically overwritten to its
oldest entries as it attains a maximum size. When it is
set to True, the capped collection feature gets enabled.

autoIndexId Boolean When this option is set to true, it automatically


generates an index on the ID field. By default, its value
is kept as false.

size Number This option is used to specify the ceiling size in bytes for
capped collection. When the capped value is set as true,
you are required to specify this field also.

max Number This option helps to specify the highest number of


documents allocated for a capped collection.

Let us take an example to see how to implement the command in MongoDB:

Example:

[Link]("MyCollection")

Output:
6/4/22, 10:17 AM Create Collection in MongoDB

MongoDB can create collections automatically as documents are inserted


automatically. Let us take a situation where you want to insert a document using
insert() in a collection named "movie"; you can type the command something like
this:

Example:

[Link]({"name":"Avengers: Endgame"})

The above operation will automatically create a collection if the collection with this name
does not currently exist. Also, if you want to check an inserted document, you can use
the find() method. Its syntax is:

db.collection_name.find()

Output
:
6/4/22, 10:20 AM Drop Collection in MongoDB

MongoDB - Drop Collection


For dropping a collection in MongoDB, you have to make use of the [Link]()
[Link] will eliminate the collection from the database completely and will not leave
any indexes that are connected to this drop collection. It is also to be noted that, this
collection dropping method has no argument in it and will pop up with errors in case
arguments are passed. All the indexes associated with the collection gets dropped once
this method is executed.

The syntax for using this method is:

Syntax:

db.collection_name.drop()

Here is an example that is showing the use of the drop() method:

Continuing from the example in the previous lesson where you have created a
collection inside the my_project_db database. Now use this database to remove or
drop the moviecollection and see the changes:

Example:

use
my_project_db
[Link]
() show
collections
Output:
Query Operations in MongoDB

MongoDB - Insert Documents


CRUD operation is one of the essential concepts of a database system. Inserting data
in the database comes under one of the CRUD operations. If you do not insert data in
your database, you will not be able to continue with other activities within your
document. In this chapter, you will learn about the different concepts and methods that
are related to the insert operation in MongoDB.

Various Insert Operations of MongoDB

The insert operation is one of the crucial operations in the database system. MongoDB
supports the below mentioned three methods to insert document data in your database:

1. insert()
2. insertOne()
3. insertMany()

The insert() Method


The insert() method is used to insert one or multiple documents in a collection. The
collection name is associated with the insert() method and the parameters. The syntax to
insert a singledocument is shown below:

Syntax:

db.collection_Name.insert(JSON document)

In the above syntax, the document will consist of { name: "data_value" }. As it is a JSON
document, these documents will consist of the data as name-value pairs, surrounded by
curlybraces, i.e. {}.
Syntax:

[Link]({"name":"Avengers: Endgame"})
[Link]()

2/3
Query Operations in MongoDB

Output:

The _id which is provided by MongoDB is a 12-byte value of ObjectId which is


prepared fromthe following values:

● a 4-byte value denoting the seconds as Unix epoch,


● a 3-byte device identifier value,
● a 2-byte processing id,
● a 3 byte counter which is a random value.

Create Multiple Documents Using insert() Method


It is also possible for you to insert multiple document values in a particular insert()

method. Let us take an example where you can insert multiple documents at a time:

Example:

[Link](
[
{ name: "Avengers: Infinity War" },
{ name: "Avengers: Endgame" }
]
)

It is to be noted that the documents are supplied in the form of an array. Document
values are packed or enclosed in square brackets [] and separated by commas.

Executing the above statements will pop up with messages something like this:

Output:

3/3
Query Operations in MongoDB

Embedded Documents
MongoDB also allow users to create document containing other documents, arrays of
values,as well as arrays of documents.

Example:

[Link]({
writername: "Stan Lee",
comics: [
{ comics: "DC Comics", year: 2004, name: "Superman" },
{ project: "DC Comics", year: 2001, level: "Batman" },
{ project: "Marvel Comics", year: 1968, level: "Captain America" }
]
})

Output:

The insertOne() Method

4/3
Query Operations in MongoDB

Another way to insert documents is by using the insertOne() method for a single
document ina collection:

Example:

[Link]({ _id: 2, writername: "Stan Lee", name: "Aquaman" })

In this case, you have a particular non-existent collection of data. In the case of the
insert() method, a precise collection will get produced in case it does not exist
previously.

Here you will observe that the output appeared to be different in format than that of
insert()method:

Output:

insertMany() Method
As the name is explaining its working, is used for inserting multiple documents:

Example:

[Link](
[
{ _id: 20, devname: "John Wick", tools: "Visual Studio", born: 1948 },
{ _id: 21, devname: "Ganesh Roy", tools: "Net Beans", born: 1945 },
{ _id: 22, devname: "Deeksha Raul", tools: "Unity 3D", born: 1954 }
]
)

Output:

5/3
Query Operations in MongoDB

MongoDB - Query Operations


Queries are another essential element of a database system. When your database is
having all the data fed into it, and you want to retrieve the data by executing some
command, MongoDB allows you to do that. In this chapter, you will learn about the
different ways of how queries can be made using MongoDB.

What Is a Database Query?


A query in a database system is a command that is used for extracting data from a
database and display it in a readable form. Every query associated with the database
system is associated with any particular language (such as SQL for structured data,
MongoDB for unstructured data). Queries can be explained by taking a suitable
example:

Let us assume a situation where your database has an employee table, and you wish to
track the sales performance ID, so you have to write a query to ask your database to
fetch for you the list of all the sales performance with the highest sales data in the top.
This is where the queries of a database language become useful.

Methods for Performing Queries in MongoDB


1. The find() method: This method is used for querying data from a MongoDB
collection. The basic syntax for using this method is:
Syntax:

db.collection_name.find()

Example:

[Link]()

Various other options can be used to make the query specific. It will be

6/3
Query Operations in MongoDB

discussedbelow.

2. The pretty() method: This method is used for giving a proper format to the
outputextracted by the query.
The basic syntax for using this method is:
Syntax:

db.collection_name.find().pretty()

Example:

[Link]().pretty()

Here is how they can be implemented:

Filtering Criteria in MongoDB Queries


It is also possible to filter your results by giving or adding some specific criteria in
which you are interested to. For example, if you wish to see the Gaurav Mandes data,
you can add a specific attribute to the find() to fetch the data of Gaurav Mandes
from that particular database.

Example:

[Link]( { author: "Gaurav Mandes" } )

Output:

MongoDB Query Which Specify "AND" Condition


MongoDB also allows you in specifying data values of the documents holding two or
more specified values to be fetched from the query. Here are two examples showing
the use ofspecifying queries using AND.

7/3
Query Operations in MongoDB

Example:

[Link]( { tools: "Visual Studio", born: 1948} )

MongoDB Query Which Specify "OR" Condition


MongoDB allows users to specify either one or multiple values to be true. According to
this, tillone of the conditions is true, the document data will get returned. Here is an
example showing the use of OR condition:

Example:

[Link]({$or: [ { instrument: "Drums" }, { born: 1945 } ] } )

Output:

8/3
Query Operations in MongoDB

MongoDB - Query Operations


Queries are another essential element of a database system. When your database is
having all the data fed into it, and you want to retrieve the data by executing some
command, MongoDB allows you to do that. In this chapter, you will learn about the
different ways of how queries can be made using MongoDB.

What Is a Database Query?


A query in a database system is a command that is used for extracting data from a
database and display it in a readable form. Every query associated with the database
system is associated with any particular language (such as SQL for structured data,
MongoDB for unstructured data). Queries can be explained by taking a suitable
example:

Let us assume a situation where your database has an employee table, and you wish to
track the sales performance ID, so you have to write a query to ask your database to
fetch for you the list of all the sales performance with the highest sales data in the top.
This is where the queries of a database language become useful.

Methods for Performing Queries in MongoDB


1. The find() method: This method is used for querying data from a MongoDB
collection. The basic syntax for using this method is:
Syntax:

db.collection_name.find()

Example:

[Link]()

Various other options can be used to make the query specific. It will be
Query Operations in MongoDB

discussedbelow.

2. The pretty() method: This method is used for giving a proper format to the
outputextracted by the query.
The basic syntax for using this method is:
Syntax:

db.collection_name.find().pretty()

Example:

[Link]().pretty()

Here is how they can be implemented:

Filtering Criteria in MongoDB Queries


It is also possible to filter your results by giving or adding some specific criteria in
which you are interested to. For example, if you wish to see the Gaurav Mandes data,
you can add a specific attribute to the find() to fetch the data of Gaurav Mandes
from that particular database.

Example:

[Link]( { author: "Gaurav Mandes" } )

Output:

MongoDB Query Which Specify "AND" Condition


MongoDB also allows you in specifying data values of the documents holding two or
more specified values to be fetched from the query. Here are two examples showing
the use ofspecifying queries using AND.
Query Operations in MongoDB

Example:

[Link]( { tools: "Visual Studio", born: 1948} )

MongoDB Query Which Specify "OR" Condition


MongoDB allows users to specify either one or multiple values to be true. According to
this, tillone of the conditions is true, the document data will get returned. Here is an
example showing the use of OR condition:

Example:

[Link]({$or: [ { instrument: "Drums" }, { born: 1945 } ] } )

Output:

$in operator
The $in operator is another special operator used in queries for providing a list of values
in the query. When your document holds any of those provided values, it gets returned.
Here is an example:

Example:

[Link]( { "instrument": { $in: [ "Keyboards", "Bass" ] } } )

Output:
6/4/22, 10:22 AM Projection Queries in MongoDB

MongoDB - Projection Queries


Various other features can be used to filter out our queries in a more precise manner.
MongoDB allows its users to add more features to a query for extracting data from the
Mongo database. In this chapter, you will learn about MongoDB Projection Queries which
can be usedfor an additional purpose.

Projection Queries
Protection queries are a particular type of MongoDB queries where you can specify
fields you want to get in the output. MongoDB allows you to perform a query for a
collection by using the [Link]() method, where you have to mention the
field that needs to be explicitly returned. This can be done by explicitly incorporating the
field names in your query, and adding a 1 or 0 with them for specifying whether this
needs to be returned or not. Such kinds of parameters are called projection parameter.
When a projection parameter is associated with a value 1, it will show the value
according to the query and hide when the projection parameter has a value 0.

Without Projection
Here is an example where the projection parameter is not used:

Example:

[Link]()

Output:
6/4/22, 10:22 AM Projection Queries in MongoDB

With Projection
Another example where the projection parameter is used:

Example:

[Link]( { "author": "Gaurav Mandes" }, { _id:0, author:1, title:1 }


)

Output:

In the example above, the _id field is excluded, which automatically gets added, and the
title
and author fields are displayed.
6/4/22, 10:22 AM Limiting Query Result in MongoDB

MongoDB - Limiting Query Result


MongoDB allows you to specify the maximum number of documents to return by
making use of the limit() method which will return only the number of documents you
need. And as soon as you prepare a MongoDB query for the collection with the help of
[Link]() method, you can add on the limit() method for specifying the
limit.

Without Limit
Here is an example where the Limit method is not used:
Example:

[Link]().pretty()

Output:
6/4/22, 10:22 AM Limiting Query Result in MongoDB

In the above example, you can see that three results are showing as output.

With Limit
Another example where the Limit method is used:

Example:

[Link]().pretty().limit(2)

Output:

In the above example where the limit() method is used, you can see that only two
results are seen in the form of output because we have passed the parameter in the
limit() method to display only two records.

Skipping Documents
It is also possible to skip some documents from a MongoDB database. You can perform
such operations using the skip() method of MongoDB. In other words, it can be said
that users have the power to manage or regulate where MongoDB begins returning the
query results.

Example:

[Link]().pretty().skip(1)
6/4/22, 10:22 AM Limiting Query Result in MongoDB

Output:
Update Documents in MongoDB

MongoDB - Update Documents


Updating the database is another essential operation that every database system must
have. If you have put some data in your database and want to alter the values of any
particular document, you need to use the update operation. In this chapter, you will
learn about how to update data within MongoDB database.

Use of Update Operation in MongoDB


The update operation in a database is used to change or update values in a document.
MongoDB makes use of the update() method for updating the documents within a
MongoDB collection. For updating any specific documents, a new criterion can be
incorporated with the update statement, which will only update the selected documents.

You have to put some specific condition in the form of the parameter to update the
documentin MongoDB. Here is a stepwise representation of how this can be performed:

● Make use of the update() method.


● Prefer the circumstance that you wish to implement for deciding which document
needs an update in their database. Let us assume an example where you want to
update your document which is having an id 4.
● Then make use of the set command for modifying the Field Name.
● Select which Field Name you wish for modifying and go into the new value
consequently.

Syntax:

[Link](
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
Update Documents in MongoDB

Example of the update() Method


First, let's select a record to update:

Example:

[Link]({ _id: 4 }).pretty()

Output:

So, now let us update the list of instrument played by this person, by making use of the
$set
operator for updating a single field.

Example:

[Link](

{_id: 4},
{
$set: { instrument: ["Vocals", "Violin", "Octapad"] }
}
)

Output:
Update Documents in MongoDB

Characteristics of Update in MongoDB


● In case your field does not subsist in the current document, the $set operator will
insert a new field with the specified value, until and unless it violates the type
constraint.
● MongoDB users can also make use of { multi: true } for updating multiple
documents which will meet the query criteria.
● Making use of { upsert: true } for creating a new document is also possible
as no document goes with the query.

save() Method in Mongo


As you have encountered so far the update() method which helps in updating the
Mongo database values in any existing document; on the other hand, the save()
method is used to replace a document with another document conceded in the form of
a parameter.

In other words, it can be said that the save() is a blend of both update() as well as
insert(). As the save() method is used, the document that exists will get updated.
Otherwise, when it does not exist, it will create one. When an _id field is not specified,
MongoDB automatically creates a document with this _id containing an ObjectId value
(as conducted by the insert()method).

Example:

[Link]({
"_id": 4,
"name": "Steven Morse",
"instrument": "Violin",
"born": 1954
})

Output:
Delete Documents in MongoDB

MongoDB - Delete Documents


After creating an updating the document, a situation might occur where you want to
delete any document or a set of documents. MongoDB also allows you to delete any
particular document or multiple collections of documents. In this chapter, you will
learn about how todelete documents from a MongoDB database.

Deleting Documents in MongoDB

MongoDB allows you to delete a document or documents collectively using its one
of the three methods. Three methods provided by MongoDB for deleting documents
are:

1. [Link]()
2. [Link]()
3. [Link]()

[Link]() Method
This method is used to delete only a single document, even when more than one
document matches with the criteria. Here is an example of using this
[Link]() method for deleting the single document. To perform this
process here, we have created a databaseand saved all the data separately.

Example:

[Link]
sert([
{ name: "James Gosling" },
{ name: "Dennis Ritchie" },
{ name: "Bjarne Stroustrup" }
]
)
Delete Documents in MongoDB

Once the insertion process is done, you can run the query (mentioned below) to
return multiple results:

Example:

[Link]()

Output:

Once you execute the above line, you will find that some documents match your query
criteria and will get displayed as output. Now, you can make use of the following criteria
to delete thedocuments.

Example:

[Link]( { name: { $in: [ "Dennis Ritchie", "Bjarne Stroustrup"]


} } )

Executing this statement, you will notice that, although two documents match the
criteria,only one document gets deleted.

Deletes Each Document


It is possible for you to delete all your existing documents in a collection by simply
excluding the filter criteria that is mentioned in the parenthesis () and specifying the
document names within it. Now, to delete all documents from the programmers'
collection, you have to write thequery like this:

Example:
Delete Documents in MongoDB

[Link]( {} )

Output:

But, when the filtering is done for removing elements, the [Link]()
method willdocument which matches the specified criteria.

Here, we delete all documents where the artist name is "James Gosling".

Example:

[Link]( { name: "James Gosling" } )

Output:

[Link]() Method
MongoDB allows you to delete multiple documents using the
[Link]() method. This method deletes all your documents
whichever match its criteria mentioned in the parameter. To check its implementation
of [Link]() method, you can use the method the same way as done
previously:

Example:

[Link]( { name: { $in: [ "Dennis Ritchie", "Bjarne


Stroustrup"
] } } )

Output:

In this way, continuing from the previous example implementation, now all the records
were also deleted, and the deleteMany() method was used this time. Now, if you try to
find the documents using find() method, it won't show any result of your query or search.
Concept of Aggregation in MongoDB

MongoDB - Concept of
Aggregation
When MongoDB users want to gather metrics from a MongoDB database, aggregation
of MongoDB is the best tool for this. Bundling the data from numerous record sources
which are then operated in various ways on a pool of data for returning a combined
result is what MongoDB allows its users. In this chapter, you will learn about the
concept of aggregation thats supported by MongoDB.

What Is Aggregation?
In MongoDB, aggregation can be defined as the operation that is used for processing
various types of data in the collection, which returns a calculated result. The concept of
aggregation mainly clusters out your data from multiple different documents which are
then used and operates in lots of ways (on these clustered data) to return a combined
result which can bring new information to the existing database. You can relate
aggregation to that of the count(*) along with the 'group by' used in SQL since both are
equivalent in terms of the working.

MongoDB offers three different ways of performing aggregation:

● The aggregation pipeline.


● The map-reduce function.
● Single purpose aggregation methods.

aggregate() Method in MongoDB


MongoDB's aggregate function will cluster out the records in the form of a collection
which can be then employed for providing operations like total number(sum), mean,
minimum and maximum, etc. from the aggregated group of data extracted.

For performing such an aggregate function, the aggregate() method is used. The
Concept of Aggregation in MongoDB

syntax of this method looks something like this:

Syntax:

db.collection_name.aggregate(aggregate_operation)

Now, let us see how the aggregate() method works:

Implementation of aggregate() Method


Consider a collection named programmers, which has the following data. You have used
the
find() method to take a look at all the different data available within it:

Example:

[Link]()

Output:

Example:

[Link]([{$group : {_id: "$type", TotalRecords: {$sum : 1}}}])

Output:

The above-executed aggregate() method will give the result shown. It says that
there are three records which do not have any specific type and are available
within the collection "programmers" for aggregating. Hence, the above aggregation
method has clustered thecollection's data in its best possible way.

Another example where we have a collection named writers, which has the following data:

Example:
Sorting in MongoDB

Now, execute the aggregate() method:

Example:

[Link]([{$group : {_id : "$author", TotalBooksWritten :


{$sum :1}}}])

Output:

Different Expressions Used by Aggregate Function

Expressi Description
on

$sum adds up the definite values of every document of a collection.

$avg computes the average values of every document of a collection.

$min finds and returns the minimum of all values from within a
collection.

$max finds and returns the maximum of all values from within a
collection.

$push feeds in the values to an array in the associated document.

$first fetches out the first document.

$last fetches out the last document.

$addToS feeds in the values to an array without duplication.


et
Sorting in MongoDB

MongoDB - Sorting
Sorting is one of the necessary database operations. It helps to simplify readability
and sort the data as per the requirement. In this chapter, you will learn about sorting
concept and how it can be implemented in the MongoDB database.

What Is Sorting in Database?


Sorting can be defined as the ordering of data in the increase as well as decreasing
manner based on a number of linear relationships among the various data items
residing in the database. Sorting can be performed on entities like information (which
includes names and facts), numbers as well as records. Sorting also increases the
readability and uniformity to thedisplayed data from the database.

sort() Method of MongoDB


For sorting your MongoDB documents, you need to make use of the sort() method. This
method will accept a document that has a list of fields and the order for sorting. For
indicating the sorting order, you have to set the value 1 or -1 with the specific entity
based on which the ordering will be set and displayed. One indicates organizing data in
ascending order while -1 indicates organizing in descending order.

Syntax:
The basic syntax for the sort() method is:

db.collection_name.find().sort({FieldName1: sort order 1 or -1, FieldName2: sort


order})

Example:
Consider a collection that is having the following data:

{ "_id" : ObjectId(5983548781331abf45ec5), "topic":"Cyber Security"}


{ "_id" : ObjectId(5565548781331aef45ec6), " topic ":"Digital Privacy"}
{ "_id" : ObjectId(5983549391331abf45ec7), " topic ":"Application Security
Engineering"}
Sorting in MongoDB

Suppose I want to get data only from the topic field from all the documents in
ascending order, then it will be executed like this:

Example:

[Link]({}, {"topic":1, _id:0}).sort({"topic":1})

MongoDB projection is used to display only selected fields of the


document. The above statement will result in:

Output:

It is to be noted that in case you do not state or explicitly define the sorting preference (1
or
-1), then, the sort() method will exhibit your documents in ascending order by

default. To display the topic field of all the techSubjects in descending order:

Example:

Keep in mind that you can also sort the documents based on the field you do
not want to display.

Metadata Sort Technique


You can also specify the sorting of parameters through a new field name for the
calculated metadata which you can specify under the $meta expression as a value.
Here is a sample document that specifies a descending sort using the metadata
"textCount":

Example:
Sorting in MongoDB

{ count: { $meta: "textCount" } }

Here this specified metadata will determine the sort

[Link] is the syntax:

Syntax:

db.collection_name.find(
<MongoDB query statement>,
{ value: { $meta: <metadataKeyword> } }
)

Output
:
[Link]({},
{ count: { $meta: "textCount" } }
).sort( { count: { $meta: "textCount" } } )

You might also like