Module 5
Module 5
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.
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:
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".
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.
(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:
Table Collection
Rows/Records/Tuples 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
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
"Edition":5
MongoDB Enterprise>
In above query we have fetched all the documents from the DBMS_Books collection and as we have nlrendv
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
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
"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:
"_id" :0bjectld('59b9649d3fca9Be61527676"),
"StudnetName': "Pramod",
"Section": "c",
"Marks" : 56,
"AdmissionDate" :1SODate("2017-09-13T17:40:45.1282")
(MU-New Syllabus we.f academic year 21-22)(M5-68) Tech-Neo Publicotions.A SACHIN SHAH Venture
"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'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.
(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:
(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.