Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 3 - FSW - Important Ques With Ans

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

UNIT - III MONGO DB


Understanding NoSQL and MongoDB – Building MongoDB Environment – User
accounts – Access control – Administering databases – Managing collections –
Connecting to MongoDB from Node.js – simple applications
Part –A Questions
1. What is NoSQL?

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.

2. Enlist the features of NoSQL.


1. The NoSQL does not follow any relational mode
2. It is either schema free or have relaxed schema. That means it does not
require specific
3. definition of schema.
4. Multiple NoSQL databases can be executed in distributed fashion.
5. It can process both unstructured and semi-structured data
6. The NoSQL have higher scalability.

3. Enlist the features of MongoDB.

1. It is a schema-less, document based database system.


2. lt provides high performance data persistence.
3. It supports multiple storage engines.
4. It has a rich query language support.
5. MongoDB provides high availability and redundancy with the help of
replication.
That means it creates multiple copies of the data and sends these
copies to a different server so that if one server fails, then the data is retrieved
from another server.

4. What is mongoDB?

 MongoDB is an open source, document based database.


 It is developed and supported by a company named 10gen which is
now known MongoDB Inc.
 The first ready version of MongoDB was released in March 2010.
5. Why MongoDB is needed?

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

6. How the terms in MongoDB are different from SQL?

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.

7. Define collections in MongoDB.

MongoDB groups data together through collections. A collection is simply a


grouping of documents that have the same or a similar purpose.
A collection acts similarly to a table in a traditional SQL database, with one
major difference.
In MongoDB, a collection is not enforced by a strict schema; instead,
documents in a collection can have a slightly different structure from one
another as needed.
This reduces the need to break items in a document into several different
tables, which is often done in SQL implementations.

8. Define the term document in MongoDB.

A document is a representation of a single entity of data in the MongoDB


database. A collection is made up of one or more related objects.
A major difference between MongoDB and SQL is that documents are
different from rows.
Row data is flat, meaning there is one column for each value in the row.
However, in MongoDB, documents can contain embedded subdocuments,
thus providing a much closer inherent data model to your applications.

9. What is User Accounts in MongoDB? List the various operations used


in UserAccounts.

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

10. Explain the createUser command in MongoDB.

The user accounts are created using the createUser() method.


Syntax
db.createUser (user, writeConcern)
Parameters
user: Is a document with authentication and access information about the
user to create.
writeConcern: This document represents the level of write concern for
creation operation.

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.

12. How remove user from MongoDB?

For removing the user, the db.dropUser() is used.


Syntax
db.dropUser(username)

13. Enlist any four data types in MongoDB.

Following are various types of data types supported by MongoDB.


1. Integer: This data type is used for storing the numerical value.
2. Boolean: This data type is used for implementing the Boolean values
i.e. true or false.
3. Double: Double is used for storing floating point data.
4. String: This is the most commonly used data type used for storing the
string values.
3
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

 Syntax for creating the user administrator account is as follows -


use admin
db.createUser(
user:"<usernamne>",
Pwd:"<password>",
Roles: ["userAdminAnyDatabase]})

14. Explain how to create collection in MongoDB

After creating some sample database, we must create some collection


inside that database.
Syntax
db.create Collection(name, options)
where
We can create collection explicitly using createCollection command
name is the name of collection
options is an optional field. This field is
maximum number of documents and so on.

15. How to Create Database in MongoDB?

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>

16. Define CRUD Operation.

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.

4
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

17. How to create Create Collection in MongoDB?

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 }

19. How to insert multiple documents in a MongoDB database?

It is possible to insert multiple documents at a time using a single


command. Following command shows how to insert multiple documents in
the existing collection
> var = allStudents =
[
{
"name": AAA,
'age": 20
},
{
“name”:BBB,
“age": 21
},
{
"name": CCC
"age": 22
}
];
>db.Student
>db.Student details.insert(alliStudents),

20. How to delete Documents in MongoDB?

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?

The methods used in Update the document in MongoDB


1.updateOne,
2. updateMany or bulkwrite.

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

connect(url,options) This method is used to connect to the MongoDB


using the specified url.
close(force, callback) This method closes the db and underlying
connections.
db(dbname, options) It creates a new DB instance sharing the current
socket connections.
isConnected(options) It checks if MongoClient is connected.

6
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

Part B & C Questions


1.Write about Understanding NoSQL and MongoDB
NoSQL

 NoSQL stands for not only SQL.


 It is nontabular database system that store data differently than
relational tables.
are various types of NoSQL databases such as document, key-value,
wide column and graph.
 Using NoSQL we can maintaın flexible schemas and these schemas
can be scaled easily with large amount of data.
Need
The NoSỌ.L database technology is usually adopted for following reasons -
1. The NoSQL databases are often used for handling big data as a part of
fundamental
architecture.
2. The NoSQL databases are used for storing and modelling structured,
semi-structured
and unstructured data.
3. For the efficient execution of database with high availability, NoSQL is
used.
4. The NoSQL database is non-relational, so it scales out better than
relational
5. databases and these can be designed with web applications.
6. For easy scalability, the NoSQL is used.
Features
1. The NoSQL does not follow any relational model.
2. It is either schema free or have relaxed schema. That means it does not
require specific definition of schema.
3. Multiple NoSQL databases can be executed in distributed fashion.
4. It can process both unstructured and semi-structured data.
5. The NoSQL have higher scalability.
6. It is cost effective.
7. It supports the data in the form of key-value pair, wide columns and
graphs.
MongoDB
 MongoDB is an open source, document based database.
 It is developed and supported by a company named 10gen which is
now known MongoDB Inc.
 The first ready version of MongoDB was released in March 2010.

7
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

Why MongoDB is needed?


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.
Features of MongoDB
1. It is a schema-less, document based database system.
2. It provides high performance data persistence.
3. It supports multiple storage engines.
4. It has a rich query language support.
5. MongoDB provides high availability and redundancy with the help of
replication. That means it creates multiple copies of the data and sends
these copies to a different server so that if one server fails, then the
data is retrieved from another server.
6. MongoDB provides horizontal scalability with the help of sharding.
Sharding means to distribute data on multiple servers.
7. In MongoDB, every field in the document is indexed as primary or
secondary. Due to which data can be searched very efficiently from the
database.

2. Give the detail about collection and document in MongoDB.

Understanding Collections

 MongoDB groups data together through collections. A collection is


simply a grouping of documents that have the same or a similar
purpose.
 A collection acts similarly to a table in a traditional SQL database,
with one major difference.
 In MongoDB, a collection is not enforced by a strict schema; instead,
documents in a collection can have a slightly different structure from
one another as needed.
 This reduces the need to break items in a document into several
different tables, which is often done in SQL implementations.

Understanding Documents

 A document is a representation of a single entity of data in the


MongoDB database. A collection is made up of one or more related
objects.
 A major difference between MongoDB and SQL is that documents are
different from rows.
 Row data is flat, meaning there is one column for each value in the
row.
 However, in MongoDB, documents can contain embedded
subdocuments, thus providing a much closer inherent data model to
your applications.
8
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

 The records in MongoDB that represent documents are stored as


BSON, which is a lightweight binary form of JSON,
with field:value pairs corresponding to JavaScript property:value
pairs.

 These field:value pairs define the values stored in the document.

 That means little translation is necessary to convert MongoDB records


back into the JavaScript object that you use in your Node.js
applications.

 For example, a document in MongoDB may be structured similarly to


the following with name, version, languages, admin, and paths fields:

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

Figure 3.1 SQL Structure Vs. MongoDB


9
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

Consider a student database as follows


To the left hand side we show the database in the form of table and to the
right hand side the database is shown in the form of collection,

Figure 3.2 Student Database in MongoDB


3. How to create users in MongoDB? Also enlist and explain various
roles of the users.
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
Let us discuss them one by one.
1. Listing Users

User accounts are stored in db.system.users collection of each database.


There exists an object named User which contains the fields like_id, user,
pwd and roles.

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.

test> use admin


switched to db admin
admin> show users
[]
admin>
admin>

As no user is created, it is showing empty.


Another query is using find). The db.system.users.find() returns a cursor
object. Then using count() method we can obtain the total number of users
present in the system. For example-

test> use admin


SWitched to db admin
admin> cursor = db.system.users.
find()
admin> cursor. count()
0
admin>

2. Create User Accounts

The user accounts are created using the createUser() method.


Syntax
db.createUser(user, writeConcern)
Parameters
user: is a document with authentication and access information about the
user to create
writeConcern: This document represents the level of write concern for
creation operation

The user document has following fields


Name Description Type
User The name of the new user. string

Pwd The user's password. The pwd field is not string


required if we run db.createUser(0 on the $
external database to create Users who have
credentials stored externally to MongoDB.
customData Any arbitrary information. This field can be documen
used to store any data an admin wishes to
associate with this particular user.

11
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

For example, this could be the user's full name


or employee id.
Roles The roles granted to the user, Can specify an array
empty array [] to create users without roles.

Table 3.1 User document fields

The role can be specified as

{role: "<role>”,db: “<database>”}

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

Creating the user with roles

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.

Table 3.2 Roles in creating user


For example -
db.createUser
user:'sysAdmin",
pwd: "pass123",
roles:['readWrive" "'dbAdmin"]
}
);

Following screenshot represents how to create user with role.

test> db.createUser(
user:sysAdmin"
pwd: "pass123"
roles: ["readWrite", "dbAdmin”]
}
);
{ ok:: 1}
test>

3. Remove Users

For removing the user, the db.dropUser() is used.

13
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

Syntax

db.dropUser(username)

For example

test> db. dropUser("sysAcin");


{ ok: 1}
test>

By above command the user named "sysadmin" is removed.


Users.
4. Explain with suitable example how to create database administrator
account in MongoDB
Access Control
 User exists in context of a single database. MongoDB provides
authentication and authorization at database level.
 For basic authentication purposes, MongoDB stores user credentials
inside a collection called system. users in each database.
 The admin database does not have any users assigned to it.
 The User administrator account provides the ability to create user
accounts in the admin and other databases.
1. Creating a User Administrator Account

 For configuring the access control, the first step is to implement


User Administrator account.
 User Administrators create users and create and assigns roles. A User
Administrators can grant any privilege in the database and can create
new ones.
 In a MongoDB deployment, create the User Administrator as the first
user. But it cannot manage the database.

 Syntax for creating the user administrator account is as follows -


use admin
db.createUser(
user:"<usernamne>",
Pwd:"<password>",
Roles: ["userAdminAnyDatabase]})

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

Note that the administrator user is now sysadmin with password


system123.we can authenticate the admin database using db.auth
coommand with user name and password options
test> use admin
switched to db admin
admin> db.auth("sysadmin”, ”system123)
If a wrong password is used then it gives the authentication error
admin> use admin
already on db admin
admin> db.auth ("sysadmin", "pass123");
MongoServerError: Authentication failed.
admin>

2. Creating Database Administrator Account

For creating a Database Administrator account, the createUser method is


used. The assign the roles such as
readWriteAnyDatabase,
dbAdminAnyDatabase,
clusterAdmin.

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

5. What are the data types used in MongoDB? Explain in detail.

Following are various types of data types supported by MongoDB.

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.

6. Write the MongoDB command to create and drop the database.


Administering Databases.

Write the MongoDB command to create and drop the database.


operations.

In this section we will discuss how to create and handle database in


MongoDB using
various commands.

(1) Create Database


For example
Open the command prompt and type the command mongosh for starting
the mongDB shell.
The test> prompt will appear. For creating a database we need to “use” the
command.
Syntax
use Database_name

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>

(2) Displaying all the databases present in the system

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.

(3) Drop Database


The dropDatabase() command is used to delete the database. For example -
Mystudents> db.dropDatabase()
{ ok: 1,dropped: ‘mystudents’ }
mystudents>

17
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

7. Explain with suitable examples, CRUD operations in MongoDB.

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.

Following is a list of such options.

Field Type Description


Capped Boolean Capped collection is a fixed size collection. It
automaticallyoverwrites the oldest entries when
it reaches to maximum size.if it is set to true,
enabled a capped collection. When you specify
this value is true, you need to specify the size
parameter.
autolndexID Boolean This field is required to create index id
automatically. Its detault value is false.
size Number This value indicates the maximum size in bytes
for a clapped collection.
Max Number It specifies the maximum number of
documents allowed in capped collection.
Table 3.3 Options for create collection
For example - Following command shows how to create collection in a
database using explicit command
test> use myStudents
Switched to db mystudents
myStudents> db.createCollection("Student_details”)
{ ok: 1 }
Mystudents>

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

The drop collection command is actually used to remove the collection


completely from the database. The drop command removes a collection
completely from database.

Syntax

db.collection name.drop()

For Example

my Students> db.Student_details.drop()
true
my Students>

We can verify the deletion of the collection by using "show collections" in


the database.

myStudents> show collections


myStudents>

4. Insert documents within the collection

The document is inserted within the collection. The document is


analogous to rows in database
Syntax
db.collection name.insert( {key, value }

For example
myStudents> show collections
nyStudents> db.create Collection("stedent details)
{ ok: 1}

myStudents> db.Student_details.insert(nameAAA" age":2})


acknowledged : true,
myStudents>
insertedIds:{ '0': 0bjectId("643e4b63436497399alala66")}
}
myStudents>

We can verify this insertion by issuing following command


myStudents> db. Student.details.find()
[{ _id: Object Id ("643e4b63436497399al a2 a66"), name: AAA, age: 22 }]
myStudents>

19
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

5. Inserting Multiple Documents


It is possible to insert multiple documents at a time using a single
command. Following program shows how to insert multiple documents in the
existing collection.
my Students> var all_students. =
[
{
“name”: “BBB”
“age":20
},
{
“name" : "DDD”
“age":21
},
];
acknowledged :true,
ent details.find()
myStudents> db.Student detaits . Insert(allstudents);
insertedIds: { ‘0’ : ObjectId ("643e518d436197399ala2a67”)
‘1': “ObiectId"643e518d436497399aia2a68”)
}
}
myStudents>

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

{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age:


21,}
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age:
20,}
]
myStudents>
Now to delete a record with name “DDD” we can issue the command as
follows-
myStudents> db.Student details.deleteOne( {“name”: “DDD” });
{ acknowledged: true, deletecount: 0}
myStudents>
Now using find() command we can verify if the desired data is deleted
or not.
myStudents> db.Student_details. find()
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 }
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age:
21,}
}

7. Delete all documents

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)

For example - Suppose the collection "Student_details” contain 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>
21
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

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
}

It can be verified using db.Student details.find() command


my Students> 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: ‘WWW’, age:
23,}
]
myStudents>

Thus the document gets updated.

By default the update command updates a single document. But we can


update multiple document as well. For that purpose we have to add

db. Student details. update({ "age"21}, ($set:{"age":23}},{multi:true})

9. Sorting

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

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>

For sorting the documents in descending order sort command is used.


myStudents> db.Student_details. find()
[
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23},
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 },
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21},
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20},
]
myStudents>

If we want to display data in ascending order, we issue following command


myStudent> db.Student_ details.find().sort{“age”:1})
For Example:
myStudents> db.Student_details. find()
[
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘DDD’, age: 20},
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘BBB’, age: 21},
{-id: ObjectId ("643e4b63436497399ala2a66"), name: ‘AAA’ ,age: 22 },
{ -íd: ObjectId ("643e518d436497399ala2a67 "), name: ‘CCC’, age: 23},
]
myStudents>

23
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

8. What are the steps to connect Node.js with MongoDB?

For connecting the Node.js with MongoDB we use MongoClient


Following are the steps used to connect Node.js with MongoDB

Step 1: Install MongobB driver for Node.js by issuing following command


on the command prompt
npm install mongodb

Step 2: In the Node.js application program require the MongoDB module


by adding following line of code

const MongoClient = require(‘mongodb’).MongoClient;

Step 3: Define MongoDB Connection URL

const url = “mongodb//127.0.0.1:27017/myStudents";

Step 4: Create the instance of MongoClient by passing the above URL to


it. It is as follows -

const client = new MongoClient(url);

Step 5: Finally use the connect method to get connected with the
database

client.connect()

The complete code is as follows -

App.js
// get the mongoDB client

const MongoClient = require('mongodb'), MongoClhent;


//Specify the URL of the database to which the connection is to be
done
const url= mongodb://127.0.0.1:27017/myStudents

//Create client instance

const client = new MongoClient(url);

//Connect to the database

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():

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 we are going to create a database.

3) Then we are using connect method by passing the above database


object is created by a database name "myStudents”.
Note that before execution of the above code, it is necessary to install the
mongodb package using the following command at the current working directory.
Prompt:>npm install mongodb
9. Explain the MongoDBClient object and the methods associated with
it.
The MongoDBClient
The MongoDBClient object provides interactions to connect to the database,
Following are some commonly used method of MongoDBClient object
Method purpose

connect( url,options) This method is used to connect to the MongoDB


using the specified url
close(force, callback) This method closes the db and underlying
connections.
db(dbname, options) It creates a new DB instance sharing the current
socket connections.
isConnected(options) It checks if MongoClient is connected.

Table 3.4 Methods in MongoDBClient

25
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

10.Explain the db object and the methods associated with it.


The db object
The db object is created for connecting to the database in MongoDB,
Following are commonly used methods of db object -

Method Purpose

addUser(username, It adds user to the database


password, callback)
admin() This method returns Admin db instance.
collection(name, options, Fetch a specific collection. The name is a
callback) collection name we wish to access. The
callback function accepts error and names
parameters where names is an array of
collection names.
Collections(options,callbacks) This method fetches all the collections for
current db.
createCollection(name, This method is used to create a new
options,call back) collection on a server with the specified
options.
dropCollection(name, It drops the collection from the database,
options, callback) removing it permanently.
listCollections(filter, options) This method is used to get the list of all
the collection information for the specified
db

Table 3.4 Methods in DBObject

26
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

11.What is CRUD? Explain the CRUD operation in Node.js.


In this section we will discuss basic CRUD operations on MongoDB. CRUD
stands for Create, Read, Update and Delete. The CRUD operations are
performed in collaboration with Node.js and MongoDB.
Prerequisite: For performing these operations we need to have MongoDB
installed in our machine. One must also install MongoDB Compass (It is a
graphical tool) to verify the operations performed by node.js on MongoDB.
Example Code: In this example, we will create a Student database with two
fields – name and city.
1.Creation of collection
Step 1: We will create a database studentDB. For that purpose make a
folder in your current
working directory. I have created the folder by a name StudentDBDemo.
Step 2: Open the command prompt go to the path of StudentDBDemo. And
issue the commands
D:\Node JSExamples\StudentDBDemo>npm init
And press enter key to accept the default values. By this package.json file
gets created. install mongodb
Step 3: Then install the mongodb module using following command
D:\Node JSExamples\StudentDBDemo>npm install
mongodb
Step 4: Now create a node.js file for creating a database and collection. The
code is as
const MongoClient = require('mongodb'), MongoClient;
Example program:create.js
create.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()
{

27
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

let result = awvait client.connect();


let dbo = result.db(database)
dbo.createCollection(“Student_Info”);
Console.log('Collection Created!!!;
}
getData():
Output is

PS E:\NodeJ SExamples\studentDBDemo> node create.js

Collection Created!!!

Programn Explanation: n above codc,

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

async function getData()


{
let result = await client.connect():
let dbo result.db(database):
var mydata = mame:"Ankita',city:"Pune'}:
dbo.collection('Student_ Info").insertOne(mydata):
console.log(Data Inserted!||"):
}
getData():

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

Figure 3.3 Multiple object inserted in document


3. Displaying (Read) the data from Collection
We can read all the documents of the collection using find method.
Following is a simple
Node.js code that shows how to read the contents of the database.

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)
db.collection("Student_ Info');

31
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

let response = await collection, find(). toArray();


console. log(response);
}
getData();

Figure 3.4 Snapshot for read the data


Program explanation: In above code,
4) First of all, we have to import the module mongodb using require. Thus
we are creating MongoDB client.
5) 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.
6) 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 accesss to studentDB.

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

Figure3.5 Snapshot for Update the object in document


5. Delete document
This is the operation in which we are simply deleting the desired document.
Here to delete a single record we have used deleteOne method.
The code as follows-
deleteOne.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: "TTT":};
}
//Delete the document
dbo.collection('Student Info"). deleteOne (mydata):
console.log('One Document Deleted");
}
getData():
34
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.

The above deletion operation can be verified by displaying the


contents of the collection

Figure3.6 Snapshot for after Delete the object in document

35
IT3501-Fullstack Web Development UNIT-3 SEMESTER-05

12.Write about sorting the document in MongoDB


Data can be arranged in sorted order in the collection. For displaying
the sorted ordered data, we use the method sort. Following code illustrates
how to display the data in ascending order of the filed named city.
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 db = result.db(database)
let collection = db.collection("Student Info"):
var mydata = {city:1}:
let response = await collection.find({}).sort(mydata).toAray();
console.log(response);
}
getData():

36

You might also like