You are on page 1of 9

G Introduction to MongoDB Shell

The mongo shell is an interactive JavaScrlpt interface to MongoDB. You can use the mongo shell to
query and update data as well as perform administrative operations.
The mongo shell is included as part of the MongoDB server installation. If you have already installed the
server, the mongo shell is installed to the same location as the server binary.

Wongoo Enterprise >a5

ongo Enterprise > a5, b 7, (- atb


rro [nterprise -

Here you can see in above image when we type 3 + 4 mongodb shell which is JavaScript enabled and
showing addiion of 3+4=7.
& Running the MongoDB shel
Let's see How to start the shell and get connected with MongoDB database.
After successful download you can get too connected with server but before that it is necessary hat the
MongoDb server instance is running and started successfully. You can verify the MongoDb server instance
"mongod" is running on machine. Aftcrwards open command prompt and navigate to MongoDb installation
directory up to bin folder and then type "mongo" command your client will gct connect to MongoDb server.
Let's see How to start the MongoDb database from binary distribution on windows machine.

(MU-New Syllabus w.e.f academic year 21-22)(MS-68) Tech-Neo Publicotions..A SACHIN SHAH Venture

Advance Database Management System (MU-Sem 5-Comp.) (NoSQL using MongoDB)...Page no.(5-3)
Step 1: Open command prompt and navigale to MongoDb insallation directory up to bin folder as shown
below.

CAWindows\system3Z\cmd.exe
Micro soft Windous [Version 6.1.7699)
Copyright (c) 2069 Microsoft Corporat ion. A11 rightc retervod.

C:\Wsers\adnin>E:

E:Sed E:\SKN DATANDBMS Lab\nongodh-vindovs-64-3.4.9\nonyodh_3.4\bin


E:\SKN DATANDEMs Lab\nongodh-uindovs -64-3.4.9\nongodh_3.4bin)

Step 2: It is necessary to start the mongodb server first before running any cient. The client and
server instances are as follows:
(1) Server Instance: - mongod
(2) Client InstAnce: - mongo

Let's start the server and while connecting create one folder on hard drive and submit the path of same folder
with server start command sop that the future work will store to the same directory.
Cwindowitsyatpm3deergod en -dboth E/svde
You can sce two red boxes in above image upper red box showing you command we need to type for starting
server the same command is as below,
mongod.exe -dbpath E/student

(MU-New Syllabus w.e.f academic year 21-22)(M5-68) Tech-Neo Publications..A SACHIN SHAH Venture

90

Acdvance Database Management System (MU-Sem 5-Comp.) (NoSQL using MongoDB)...Page no. (5-4)
Here mongod.exe will be a exe to start the server instance mongod and E:/student is folder crealed on hard
drive and it is being passed here while starting scrver.
Step 3: Now as we have scen step 2 we have started mongodb server just keep the same
command prompt
running and open new command prompt to run the client and start the client with the help of following
command "mongo.exe student".

E\SNN DATA\ D$ VS Lab\monodb wIndons


-64-3.4.91ongodb 3.4bin>rong9.exe tudent
MngoD8 server versaon: 7.0.0.1:27017 student
Server has 3tartup warnings
01-07-05TOO :19:4S.S12.0530 : cONTROL [1n1t3ndlisten)
03O9:4S.S12-0S30 1 CONTROL
in1tandlisten ARNING: ACCe35 control 13 not enabled for the dstat33e.
021-07-0$ TOO:19:45 SIe053n: o 1nitandlisten)* Read and nrite acces3 to data 3nd configuration
2021-07 -05TO0 : 19:45.SIl-05 30 I CONTROL
l-07-0STO0:19:4S.S13-0530 I cONTROL (hntandlisten Motfi kB2731254 or later update 15 nct n5ta11ed, wil1 zer
0D5 Enterprise >

Here in this above image you can see we have started client by using mongo.exe student this command and it
is started because our server is running on port number 27017 on local host and directory (student) get
configured. Everything is fine.
Hence we have successfully started the mongodb server and client through the mongodb shell let's try
various CRUD operation on mongodb database in next section.
various CRUD operation on mongodb database in next section.

a 5.1.1 MongoDB Cient


As above we have seen the server started in one command prompt with the help of proper command and if
everything is fine it is started on local host on port no 27017. Now the time is to run the client we bave to
run the client and ultimately it will open a connection with the mongodb server
running on a port it
connection is successful then we will get a access to the database directory selected at the time of starting the
server.

We can start running client instance mongo by just executing mongo.exe in


separate command prompt and
while calling select the database directory where we need to connect.
Command is :- >mongo.exe Student

(MU-New Syllabus w.e.f acadenic year 21-22XM5-68) ech-Neo Publicotions.A SACHIN SHAH Venture

Advance Database Management System (MU-Sem 5-Comp.) (NosQL using MongoD)..Page no.(5-5)

tatlssta1N:
Itaist

Nttini

In above image the command shown on red box is to start the mongodb client instance and it will be going
to connect with mongodb server which is already running on 27017 port on local hOst.

a 5.1.2 Comparatcve Analyss of SQL Database Objects and NoSQL Database Objects
The comparative analysis for the various database objects of SQL and replaced with NoSQL databases
areas below:

SQL Databases NoSQL Databases


Database Database

Table Collection

Rows/Records/Tuples Documents

Primary key Object Id Cid) filed for


document.

SQL Join Bmbedded Documents

As per above the various objects are identified with respect to SQL and NoSQL databases.
a5.1.3 Baskc Operadons with MongoDB Sbell
After installation is successful then it is shown at the server end that one connection to the server is open and
then we can start executing commands through mongodb client.
Few basic administrative mongodb database commands are as mentioned below,
(1) To display version of mongodb database we are using:
MongoDB Enterprise >rersion0;
3.4.

(MU-New Syllabus w.ef aademikc vear 21-22\M5-68) ech-eo PublicotionsA SACHIN SHAH Ventur

Advance Database Management System (MU-Sem 5-Comp.) (NoSOL uing MongoDB)...Page no. (5-6)
(2) To display the belp manual for mongodb commands you can use,
db.belp 0;
It show the help options for acollection methods also by following way,
db.<Collection_name>.help(0;
(3) To display the list of databases in mongodb:
showdbs:
or

show databases;
(4) To display the list of collections from the curent databases:
show collections;
(5) To display the list of users of current database:
show users;
(6) To display the various roles of the users from current databases:
show roles;

b'sytrendee-nogo ee
CWdos Stcent

deint

i true,

"irherited®oles": I

dhüner
1341ltin" : true,

*inheritedRoles* : |

role : "erablehanding",
3:sknzoe,
Blti : true,

-iberits :L|

-kultin* ; true,
roles :|J.
inneritestoles" LU

(MU-New Sylabus we.f academic year 21-22)(M5-68) LW Tech-Neo Publicotions. ASACHIN SHAH Venture

Advance Database Management Syslem (MU-Sem 5-Comp. (NoSQL using MongoDB)....Page no. (5-7)
(7) To create new database in mongodb database: - Let's create Books database.
use Books

This command will create Books database in mongodb and select the same as a current database. Please
note one thing here until and unless you don't have any collection created in the empty database it will
not be displayed in the list shown by show dbs command;
(8) To create collection in database we may use below command:
db.ereateCollection("Collection Name"):
5.2 QUERYING MONGODB USING FIND() FUNCTIONS

In MongoDB, find) method is used to select documents in a collection and return a cursor to the selected
documents. Cursor means a pointer that points toa document, when we use find) method it returnsa pointer
on the selected documents and returns one by one.
If we want to return pointer on all documents then use empty0 parameter that returns all documents one by
one. It takes only some optional parameters,
The first optional parameter is the sclection criteria on which we want to return a cursor. To returm all
documents in a collection use empty document(})

(MU-New Syllabus w.e.f academic year 21-22)(M5-68) d Tech-Neo Publications.A SACHIN SHAH Venture

(NoSQL uolng MongoDB)...Pago no, (6-13)


Advance Database Managemont System (MU-Sem 5-Comp.)
and NoSQL operation and alrondy we have discusscd
As we have gone through the many SQL operations ways to fotch the
from thc table in varicty of ways now let's soc the difforont
about the finding information
data from the Mongodb collections.
(1) Selecting the Information from the collectlon
Syntax :-db.collection.find(query, projection)
MongoDB Enterprise >db.DBMS_Books.find()-proltly0;

id" :0bjectld("60e7a339632c0426266f6ob7),
"Rook id: 1,
"Book Nane": "Insloduction to DBMS",
"Author":"Korth",
"Edition":6

(
"id" :0bjectld('60e7a377632e042e266f6cb8).
"Rook_id" :2,
"Book Name": "Complete Guide to DBMS",
"Author":"Desai",
"Edition":4

"id" :0bjeold("6Oebec6bfdl a80d08c3cd489"),


"Book id :3,
"Book Name": "Introduction to Java",
"Author":[
"Ghosling",
"Adam"

"Edition":5

MongoDB Enterprise>
In above query we have fetched all the documents from the DBMS_Books collection and as we have nlrendv

discussed pretty0 function is used to display the documents in formatted way,

(MU-New Syllabus w.e.f academic year 21-22)(M5-63)


Hech-Neo Publlcotions.A SACHIN SHAH Venture

Advance Database Management System (MU-Sem 5-Comp.) (NosOL using MongoDB).Page no. (5-14)
(2) To find a specific document from the collection with a specific
condition we can use below command.
MongoDB Enterprise >dbStudent.ind({Marks: 56}).pretty (0:

id" :0bjectld("59b961943fca9Be61527676).
(2) Demonstrate the use of indOne0:Similarly with findÌ function findOne) function displays
document from the collection. the first

MongoDB Enterprise >db.Student.GndOne0;


" id' :0bjectld("5952d7196R0568336449e0c9"),
"StudentName":"Tarun",
"Section":"A",
"Marks" : 105,
"Subject": J.
"AdmissionDate" :1SODate("2017-09-13T17:37:09.022Z2")

MongoDB Enterprise >


(3) Sort the documents in ascending or descending order:
Here sort0 function is used for sorting the documents in
ascending or descending order as below.
Sorting documents in ascending order :
Syntax :-db.collection.indQ.sort((key: 1})

Sorting documents in descending order:


Syntax :-db.collection.find).sort((key: -1})

For example :- Lets display the documents according to ascending order of Marks.
MongoDB Enterprise >db.Student.find0-pretty).sort({Marks :1});

(MU-New Sylabus w.e.f academic year 21-22)(M5-68) Tech-Neo PublicationsA SACHIN SHAH Venture

dvance Database Management System(MU-Sem5-Comp.) (NoSQL using MongoDB)...Page no. (5-15)

"_jd" :0bjectld('59b964943fca9fBe61 527676),


"StudnetName": "Pramod",
"Section" : "c',
"Marks": S56,
"AdmissionDate :1SODate("2017-09-13T17:40:45.128Z")

" id" :0bjectld("59b96d863fca918e61527675),


"StudnetName":"Atish",
"Section" : "B",
"Marks" : 78,
"AdmissionDate" :1SODate("2017-09-13T17:40:22.257Z")

" id" :0bjectld("5962d7266f0568336449e0ca),


"StudentName": "Saurabh"
"Section" :"A".
"Marks":95,
"AdmissionDate" :ISODate("2017-09-13T17:37:09.0222")

" id" :0bjecld('59b2d7196f0568336449eOc9"),


"StudentName" :Tarun",
"Section" :"A",
"Marks" : 105,

"Subject" : [O,
"AdmissionDate" :1SODate"2017-09-13T17:37:09.022Z")

}
MongoDB Enterprise>
number of
output of find() function and limit can only display the
(4) We can use the limit() function to filter the
documents specified with the limit function.
function as.
documents from the collection we can use the limit
For example we want to display only 2

Tech-Neo Publicotions..A
Tech-Neo SACHIN SHAH Venture
(MU-New Syllabus w.e.f academic year 21-22)(MS-68)
ß Advanced querles using loglcal operators and sorting
We can use the logical operators in MongoDB database when ever somo logicnl relatlon we requircd such as,
AND and OR operators we can use and the syntax to use logical operators as below,
Let's select a range of students whose marks is greater than 50 and less than 80
G $AND operator in mnongodb:

MongoDB Enterprise >db.Student.find({Marks: {Sgt: 50, $l: 80 }}).pretty):

" id" :0bjectld("59b96d863fca9Be61527675"),


"SudnetName":"Atish",
"Section": "B",
"Marks" : 78,
"AdmissionDate" :1SODate("2017-09-13T17:40:22.2572")

"_id" :0bjectld('59b9649d3fca9Be61527676"),
"StudnetName': "Pramod",
"Section": "c",
"Marks" : 56,
"AdmissionDate" :1SODate("2017-09-13T17:40:45.1282")

MongoDB Enterprise >


Similarly we can use $gte for greater thun ar equal to and lte for losa thanor equal to.
Let's select the students whose marks is either 56 or 78 and display the content in fornatted way.
S Logical Operator -$not
The MongoDB $not operator performs a logical NOT operation on the given expression and fetches selected
documents that do not match the expression and the document that do not contain the ficld as well: snecificd in
the expression.

(MU-New Syllabus we.f academic year 21-22)(M5-68) Tech-Neo Publicotions.A SACHIN SHAH Venture

Advance Database Management System(MU-Sem 5-Comp.) (NoSQL using MongoDB)...Page no.(5-19)


Syntax

field: { Snot: {<exprossion> )}}


If we want to select all documents from the collection "student" which satisfying the condition
Marks of the student is at least 40
the following mongodb command can be used :
>db.student.find( ("Marks"': (Snot: {$lt : 50}}})-prety0:

$OR operator in mongodb:


MongoDB Enlerprise >db.Student.find({$or: [{Marks : 56), {Marks : 78})))-prelty 0;

"jd" :0bjectld("59b96d863fca9f8e61527675"),
"StudnetName": "Atish",
"Section" : "B",
"Marks": 78,
"AdmissionDate" :1SODate("2017-09-13T17:40:22.257Z")

"_id" :0bjectld("59b961943fca9f8e61527676"),
"StudnetName":"Pramod",
"Section" : "c",
"Marks": 56,
"AdmissionDate" :ISODate("2017-09-13T17:40:45.1282")

MongoDB Enterprise >


A5.2.1 Sorting n mongodb
Sorting the documents in mongodb we can arrange the documents in ascending order or descending order

depends upon the requirements,


db.student.find).s0rt({Marks: 1).pretty)
Above statement we have already executed in last point and we have seen Marks :1 will display the
documents in ascending order of marks.
G Simple aggregate functions
Data records are processed and computed results are returned through aggregation processes. Aggregation
operations combine values from several documents into a single result and can execute a number of functions on
the gathercd data. Aggregation is performed in MongoDB sing three approaches: the aggregation pipeline, the
map-reduce function, and single-purpose aggregation methods.
S Aggregation

MongoDB's aggregation pipeline framework is modelled on the basic concept of data processing pipelines
when we aggregate the documents enter into multi stage pipeline that transforms the document into aggregated
results.
Wndoesytem3ondee-moncn Sh

You can see in the above example we have executed simple aggregate operation in first half of the query
Smatch will start matching the records with given key over there such as we have given (Section: A), so all
records who has Section: Agrouped together and in second half we have aggregated the result by taking sum of
mark of students who bave Section: A.

S Saving and updating document


SAVE method
The db.collection.save ) method is used to updates an existing document or inserts a new document,
depending on its document parámeter.
Syntax
db.collection.save( )
G Parameters

Name Descriptlon Required .


Optional
document A document to save to the collection. Required:
writeConcern A document expressing the write concern. Omit Optional
to use the default write concen.

Example: Save a New Document without Specifýing an _id Field.

(MU-New Syllabus w.e.f academic year 21-22)M5-68) Tech-Neo Publicotions.A SACHIN SHAH Venture

Adance Databese Manegement Sslem(MU-Sem 5-Comp.) (NoSOL using MongoDB)....Page no. (5-21)
In the folowing erample, savemethod performs an insert since the document passed to the method does not
ontain the id field:

>binvoixe.save( {inv_oo: "1001", iny_date: "10/102020", ord_gty:200 ) ):


>WiteResult( ninserted: 1 ))
During the insert, the shell will create the id field with a unique Objectld value, as verified by the inserted
document:

Example: Replace an Existing Document


The products collection contains the following document:
{id: 1001, "inv_Do°:"1001", "iny_date":"10/12020", "ord_gty" :200
The save) method performs an update with upsert: true since the document contains an _id field
b invoice.save( id: 1001,iny_no: "I00015", iny_date: "1S/10/2020", ord_qty:S00 ) ):
S Update Operations
Update operations modify existing documents in a collection. MongoDB provides the following mehods 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 idenify the documents to update. These filters use the same syntax as
read operations.
MongoDB Enterprise>db.Sudentupdate One({StudentName :"Atish"), (Sset : (Marks : 70))):
{"acknowledged" : true, "matchedCount": 1, "modificdCount" : 1)
MongoDB Enterprise >
With this update statement we can update the marks of student and we can set new marks using Sset
Advance Database Management System (MU-Sem (NoSQL using MongoDB)...Page no. (5-22)
5-Comp.)
a 5.2.2(A) Repllcatlon In MongoDB
A replica set in MongoDB is a group of mongod processes that maintain the same data set. Replica sets
provide redundancy and high availability, and are the basis for all production deployments. This section
introduces replication in MongoDB as well as the components and architecture of replica scts.
Sharding is a process of splitting up the large scale of data sets into a chunk of smaller data sets across
multiple MongoDB instances in a distributed environment.
MongoDB sharding provides us scalable solution to store a large amount of data among the number of
servers rather than storing on a single server.
In practical terms, it is not feasible to store exponentially growing data on a single
machine. Querying a huge
amount of data stored on a single server could lead to high resource utilization and
may not provide
satisfactory read and write throughput.
Basically, there are two types of scaling methods that exist to undertake growing data with the
system :
(1) Vertical (2) Horizontal
Vertical Scaling works with enhancing single server performance by adding more
powerful processors,
upgrading RAM, or adding more disk space to the system. But there are the possible implications of applying
vertical scaling in practical use cases with existing technology and hardware configurations.
Horizontal Scaling works with adding more servers and distribute the load on multiple servers. Since each
machine will be handling the subsct of the whole datasct, it provides better efficiency and
solution rather than deploying the high-end hardware. But it requires additional maintenancecost-effective
of complex
infrastructure with a large number of servers.
A 5.2.2(B) Sharding
Components1i"aun)beitiuot".o3iltout
Shard is a Mongo instance to handle a subset of original data. Shards are
required to be deployed in the
replica set.
Mongos is a Mongo instance and acts as an interface between a client application and a
sharded cluster. It
works asa query router to shards.
Config Server is a Mongo instance which stores metadata information and
configuration details of cluster.
MongoDB requires the config server to be deployed as areplica set.
5.2.3 Benefits of Sharding over Repllcatlon s

(1) Inreplication, the primary node handles all write operations, whereas secondary servers are required to
maintain backup copies or serye read-only operations. But in sharding along with
distributed among numbers of servers. replica sets, the load gets
(2) A single replica set is limited to 12 nodes, but there is no
restriction on the number of shards

(MU-New Syllabus w.e.f academic year 21-22)(MS-68) Tech-Neo Publications..A SACHIN SHAH Venture

Advance Database Management System (MU-Sem 5-Comp.) (NoSQL using MongoDB)...Page no. (5-23)
(3) Replication requires high-end hardware or vertical scaling for handling large dtasets, which is too expensive
compared to adding additional servers in sharding.
(4) In replication, read performance can be enhanced by adding more slave/secondary servers, whereas, in
sharding, both read and write performance will be enhanced by adding morce shards nodes.

M 5.3 DESCRIPTIVE QUESTIONS

You might also like