Unit 3 - FSW - Important Ques With Ans
Unit 3 - FSW - Important Ques With Ans
Unit 3 - FSW - Important Ques With Ans
NoSQL stands for not only SQL. It is nontabular database system that
store data differently than relational tables. There are various types of
NoSQL databases such document, key-value, wide column and graph.
Using NoSQL we can maintain flexible schemas and these schemas can
be scaled easily with large amount of data.
4. What is mongoDB?
There are so many efficient RDBMS products available in the market, then
why do we need MongoDB? Well, all the modern applications require Big
data, faster development and flexible deployment. This need is satisfied by
the document based database like MongoDB.
1
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
The terms in SQL are treated differently in MongoDB. In MongoDB the data
is not stored in tables, instead of that, the there is a concept called
collection which is analogous to the tables. In the same manner the rows
in RDBMS are called documents in MongoDB, likewise the columns of the
record in RDBMS are called fields.
MongoDB stores the information of all the users including name, password
and user authentication in the system.
Using MongoDB shell command, we can create the user accounts. Using
such user accounts, we can read and write to the databases.
The most commonly used operations are
1. List the users
2. Create the user accounts
3. Remove the users
2
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
11. List and explain the roles used in creating the user.
Role Description
read Allows the user to read data from any collection within
database.
readAnyDatabase It is similar to read except on the local and config
database.
readWrite This role provides all the privileges of the read role plus
ability to modify data on all non-system collections.
dbAdmin This role allows the user to read from and write to the
database as well as clean, modify, compact, get
statistics profile and perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.
userAdmin This role allows the user to create and modify user
accounts the database.
userAdminAnyDatabase Same as userAdmin cxcept on the local and config
databases.
The test> prompt will appear. For creating a database we need to “use”
the
command.
Syntax
use Database_name
Example
test> use mystudents
Switched to db mystudents
mystudents>
switched to db mystudents
To check the currently selected database, use the command db
mystudents> db
mystudents
mystudents>
4
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Syntax
We can create collection explicitly using createCollection command.
db.create Collection(name, options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters
such as Size, maximum number of documents and so on.
18. Give the syntax for insert the document. The document is analogous
to rows in database.
The document is inserted within the collection. The document is
analogous to rows in database
Syntax
db.collection name.insert( {key, value }
For deleting the document, the remove command is used. This is the
simplest command
Syntax
db.collection_name.remove(delete_criteria)
5
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
21. What are the methods used in Update the document in MongoDB?
22. What is the method used for sorting the document in MongoDB?
We can use the sort() method for arranging the documents in ascending
or descending order based on particular field of document.
Syntax
For displaying the documents in ascending order we should pass value 1
db collection name. find().sort ({field name:1})
If we pass -1 then the document will be displayed in the descending order
of the field
23. Explain the MongoDBCIient methods in detail.
Method Purpose
6
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
7
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Understanding Collections
Understanding Documents
{
name: "New Project",
version: 1,
languages: ["JavaScript", "HTML", "CSS"],
admin: {name: "Brad", password: "****"},
paths: {temp: "/tmp", project: "/opt/project", html:
"/opt/project/html"}
}
SQL Structure Vs. MongoDB
Following Fig. 3.1 shows the terms in SQL are treated differently in
MongoDB. In MongoDB the data is not stored in tables, instead of that, there
is a concept called collection which is analogous to the tables. In the same
manner the rows in RDBMS are called documents in MongoDB, likewise the
columns of the record in RDBMS are called fields.
10
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
For listing the users in the system, switch to admin database and then
use show users command.
11
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
For example-
admin> use test
switched to db test
test> db.createUser(
{
user: "AAA",
pwd: "AAA123",
roles: [ ]
}
):
{ ok: 1}
test>
Now to test, if the user named Parth is created or not, we issue the show
users command at the MongoDB shell.
test> show users
id: test.AAA
user: 'AAA ',
userId: new UUID("59bb3031-f90f-4dle-9749-801469ele645)
user:’ AAA’,
db: 'test',
roles: [],
mechanisms : [ 'SCRAM-SHA-1', SCRAM-SHA-256 ]
test>
The above user is created without any role. But we can assign the role to the
user during the createUser command.
12
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Following is the list of some commonly used roles that can be assigned to
their user account.
Role Description
Read Allows the user to read data from any collection within
database.
readAnyDatabase It is similar to read except on the local and config
database.
readWrite This role provides all the privileges of the read role plus
ability to modify data on all non-system collections.
dbAdmin This role allows the user to read from and write to the
database as well as clean, modify, compact, get
statistics profile and perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases.
userAdmin This role allows the user to create and modify user
accounts the database.
userAdminAnyDatabase Same as userAdmin cxcept on the local and config
databases.
test> db.createUser(
user:sysAdmin"
pwd: "pass123"
roles: ["readWrite", "dbAdmin”]
}
);
{ ok:: 1}
test>
3. Remove Users
13
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Syntax
db.dropUser(username)
For example
For example
test> use admin
switched to db admin
admin> db.createUser(
{
user:"sysadmin”,
14
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
pwd:"system123”,
roles: [“userAdminAnyDatabase”]})
{ ok: 1 }
admin> show users
For Example
test> use admin
Switched to db admin
admin> db.createUser(
user: "dbAdmin",
pwd: password123"
admin>
roles:
["readWriteAnyDatabase","dbAdminAnyDatabase""clusterAdmin"]
}
);
{ ok: 1 }
admin>
We can use this user in MongoDB shell to administer the database.
15
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
1. Integer: This data type is used for storing the numerical value.
2. Boolean: This data type is used for implementing the Boolean values
ie.true or false.
3. String: This is the most commonly used data type used for storing the
string values
4. Double: Double is used for storing floating point data.
5. Min/Max keys: This data type is used to compare a value against the
highest BSON element.
6. Arrays: For storing an array or list of multiple values in one key, this
data used.
7. Object: The object is implemented for embedded documents.
8. Symbol: This data type is similar to string data type. This data type is
used specific symbol type.
9. Null: For storing the null yalues this data type is used.
10. Date: This data type is used to store current date or time. We can also
own date or time object.
11. Binary data: In order to store binary data, we need to use this data
type.
12. Regular expression: This data type is used to store regular
expression.
Example
test> use mystudents
16
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Switched to db mystudents
mystudents>
d to db mystudents
To check the currently selected database, use the command db
mystudents> db
mystudents
mystudents>
We can see the list of databases present in the MongoDB using the
command show dbs
For example
mystudents> show dbs
Admin 180.06 KiB
config 72.00 KiB
Local 72.00 kiB
mystudents>
Note that in above listing we can not see the mystudents database. This is
because we have not inserted any document into it. To get the name of the
database in the listing by means of show command, there should be some
record present in the database.
17
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Managing Collections
After creating some sample database, we must create some collection
inside that database.We can perform various operations such as insert,
delete and update on this collection. These operations are called CRUD
operations. CRUD stands for Create, Read. Update and Delete operation.
1. Create Collection
Syntax
We can create collection explicitly using createCollection command.
db.create Collection(name, options)
where
name is the name of collection
options is an optional field. This field is used to specify some parameters
such as Size, maximum number of documents and so on.
2. Display Collection
To check the created collection use the command "show collections" at the
commarnd prompt
myStudents> show collections
Student_details
18
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
myStudents>
3. Drop Collection
Syntax
db.collection name.drop()
For Example
my Students> db.Student_details.drop()
true
my Students>
For example
myStudents> show collections
nyStudents> db.create Collection("stedent details)
{ ok: 1}
19
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
To verify the existence of these documents in the collection you can use find
command as
follows -
myStudents> db.Student_details. find()
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age:
21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age:
20,}
}
myStudents>
6. Delete Documents
For deleting the document, the remove command is used. This is the
simplest command
Syntax
db.collection_name.remove(delete_criteria)
For example
First of all we can find out the documents presents in the collection using
find() command
myStudents> db.Student_details. find()
[
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
20
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
For deleting all the documents from the collection,we can use.deleteMany()
For example
myStudents> db.Student details.deleteMany( { });
{ acknowledged: true, deletecount:2}
myStudents>
We can verify it using db.Student_details.find() command,we can verify that
records are deleted or not.
myStudents> db.Student_details. find()
myStudents>
8. Update Documents
For updating the document, we have to provide some criteria based on
which the document can be updated.
db.collection_name.update(criteria, update_data)
And we want to change the name CCC" to WWW", then the command
can be issued as
myStudents>db.Student_detaits.update({“name:”CCC”},{set:{“name”:”WWW”}}
)
DeprecationlWarning: Collection. update () is deprecated. Use updateOne,
updateMany, or bulkwrite.
{
acknowledged : true,
InsertedId: null,
matchedCount: 1,
modifiedCount:1,
upsertedCount:0
}
9. Sorting
22
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
For example
Suppose the collection contains following documents.
myStudents> db.Student_details. find()
[
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23,}
]
myStudents>
23
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Step 5: Finally use the connect method to get connected with the
database
client.connect()
App.js
// get the mongoDB client
function getData()
{
client.connect()
then(() =>console.log ("Connected to Database Successtully!!!”))
catch(error=> console.log(Failed to Connect’,error)
}
24
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
getData():
25
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Method Purpose
26
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
27
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Collection Created!!!
2) Insertion of document
1) First of all. we have to import the module mongodb' using require, Thus
we are creating mongodb client
2) Then specify the URL for MongoDB by means of hostname (localhost or
127.0.0.1)
and port number on which MongoDB is running (27017). This is a path at
which we are going to create a database.
3) Then we are using connect method by passing the above URL. Inside this
function a database object is created by a database name "studentsDB".
4) Then using the method createCollection for database object we can
create a collection inside the database "studentsDB", Note that here the
collection name is "Student_Info".
5) The message "Collection Created!!!" is displayed on the console using
console.log method.
Once the collection is created, we can insert some document into it.
Following is an example code which shows how to insert one document
into a collection named Student_info
const MongoClient = require(mongodb).MongoClient;
const url='mongodb://127.0.0.1:27017";
const client = new MongoClient(url):
// Connect to the database
const database = "studentsDB":
28
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
Output is
PS E:\NodeJ SExamples\studentDBDemo> node insert.js
Data Inserted !!!
Program explanation: In above code,
1. First of all, we have to import the module 'mongodb' using require.
Thus we are creating MongoDB client.
2. Then specify the URL for MongoDB by means of hostname(localhost)
and port number on which MongoDB is running(27017). This is a
path at which our database exists.
3. Then we are using connect method by passing the above URL. Inside
this function a database object is created by a database name
studentDB". Thus now we can access to studentDB
4. Then a JSON object is in the form {name:value}. We insert data in the
collection in the form of document. This document is čreated in the
form of JSON, Hence the mydata object is created with some values.
This mydata is inserted into the collection using insertOne method
using following code
dbo.collection ("Student Info"),insertOne(mydata)
In the same manner we can insert many documents in the collection.
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://127.0.0.1.27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
29
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
{
let result = awvait client.connect();
let dbo = result.db(database)
var mydata =[
{ name: “BBB”, city: "Mumbai" },
{ name: “CCC”, city: "Chennai' },
{ name: “DDD”, city: "Delhi' }.
{ name: "EEE”, city: "Ahmedabad'" }
dbo.collection('Student Info"). insertMany (mydata);
console. log(“Multiple documents Inserted!!!");
getData();
Output is
PS E: \Node JSExamples\studentDBDemO node insertMany.js
Multiple documents Inserted!!!
Program explanation: In above code we have created array of values in
JSON object as follows
var mydata =[
{ name: "BBB", city: "Mumbai" },
{ name: "CCC", city: "Chennai' },
{ name: "DDD', city: "Delhi' },
{ name: "EEE", city: "Ahmedabad'}
];
Then using the insertMany command we can insert all the above
documents at a time This program execution can be verified in MongoDB
compass.
Open MongobB Compass, just connect with mongodb://localhost:27017,
select the StudentDB database and then select Student Info collection. The
following screenshot displays multiple documents inserted into it.
30
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
31
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
32
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
4. Update document
Then for reading the contents present in the documents of the collection we
use the find() method.
We use to Array method associated with the fimd() because it returns an
array that contains all documents returned by the cursor.
We can modify the document using updateOne method. Following code
illustrates it -
Update.js
const MongoClient = require('mongodb'), MongoClient;
const url =”mongodb://127.0.0.1.27017”;
const client new MongoClient(url);
//Connect to the dabase
const clatabase = "studontsDB;
async function getData()
{
let result = awvait client.connect();
let dbo = result.db(database)
var mydata = { name: "DDD'};
var newdata = {$set: name:"TTT”, city:" Jaypur”}
dbo.collection("Student Info").updateOne (mydata newdata);
console.log ("One Document Updated!");
}
getData);
Output
PS E:\NodeJSExamples\studentDBDenO> node update. js
One Document Updated!!!
We can verify the above updation in MongoDB Compass. Just open the
database StudentDB using MongoDB Compass to see the modification.
33
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
OUTPUT
PS E:\NodeJ SExamples \studentDBDemo> node deleteOne.js
One DocUment Deleted!!!
We can verify it using MongoDB Compass. Note that the name TTT" is
missing.
35
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05
36