ADVANCED WEB PROGRAMMING (3161611)
B. E. in Information Technology Engineering
Database Programming with Node JS and MongoDB
Prof. Chintan Makwana
Assistant Professor
Information Technology Department
Shantilal Shah Engineering College, Bhavnagar
[Link]/view/chintanmakwana
EVEN – 2023 Term
Gujarat Technological University
1
Outline
• Basics of MongoDB
• Data types
• Connect Node JS with MongoDB
• Operations on data (Insert, Find, Query, Sort, Delete, Update) using Node JS
2
Basics of MongoDB
• MongoDB is cross-platform, open-source, document-oriented, no sequel
(NoSQL) database.
• NoSQL, also referred to as “not only SQL”, “non-SQL”, is an approach to
database design that enables the storage and querying of data outside the
traditional structures found in relational databases.
• Instead of storing your data in tables and rows as you would with a relational
database, in MongoDB you store JSON-like documents.
• mongoDB = “Humongous DB”
• Open-source
• Document-oriented
• “High performance, high availability”
• Automatic scaling 3
Basics of MongoDB
4
Basics of MongoDB
• Documents store data with the help of key-value pair.
• A Collection is a group of documents.
• These collections are stored in the MongoDB database.
SQL mongoDB
Row / Tuple Document (JSON, BSON)
Table Collection
Database Database
5
Basics of MongoDB
• JSON (JavaScript Object Notation)
• Easy for humans to write/read, easy for computers to parse/generate
• Objects can be nested
• Built on
• name/value pairs
• BSON (Binary JavaScript Object Notation)
• Binary-encoded serialization of JSON-like docs
• Goals
• Lightweight
• Traversable
• Efficient (decoding and encoding)
6
Basics of MongoDB
• BSON Example ( Key : Value )
{
“rollno" : “6001”,
“name" : “Rahul"
}
7
Data types of MongoDB
• Int32 / Int64
• String
• Boolean
• Binary
• Double
• Decimal128
• MinKey / MaxKey
• Array
• Object / ObjectId
• Symbol
• Null
• Date
• TimeStamp
• BSONRegExp / BSONSymbol
• Undefined 8
Applications of MongoDB
• Internet of Things
• Mobile Application
• Real time analysis
• Personalization
• Catalog management
• Content management
9
Features of MongoDB
• Ad-hoc queries for optimized, real-time analytics
• Indexing appropriately for better query executions
• Replication for better data availability and stability
• Sharding
• Load balancing
• Detail Reference : [Link]
10
Download MongoDB for Windows
• Download Link-1 : [Link]
• Download Link-2 : [Link]
11
Download MongoDB for Windows
12
Install MongoDB on Windows
• Installation Steps :
[Link]
ET0zpP9qJHVO4aC6E&index=4
13
Download MongoDB Shell on Windows
• Download Link : [Link]
14
Download MongoDB Shell on Windows
15
Install MongoDB Shell on Windows
• Installation Steps:
[Link]
16
MongoDB Shell Commands
(1) Database related Commands
(2) Collection related Commands
(3) Document related Commands
17
MongoDB Shell Database Commands
(1) Create Database
Syntax: use Database_name
Example: use PracticeDB
(2) Display Database
Syntax: show dbs
(3) Drop Database
Syntax: [Link]()
18
MongoDB Shell Collection Commands
(1) Create Collections
Syntax: [Link](name)
Example: [Link](“students”)
(2) Display Collection
Syntax: show collections
(3) Drop Collection
Syntax: db.collection_name.drop()
Example: [Link]()
19
MongoDB Shell Document Commands
• List of CRUD Operations for Documents
1. Create
2. Read
3. Update
4. Delete
20
MongoDB Create Operations
• Create or insert operations add new documents to a collection. If the collection
does not currently exist, insert operations will create the collection.
• Syntax:
• [Link]()
• [Link]()
• Example:
• [Link] ( { rollno:6001 , name: “Umang” } )
• [Link] ([
{ rollno:6002 , name: “Dhaval” } ,
{ rollno:6003 , name: “Ajay” }
]) 21
MongoDB Read Operations
• Read operations retrieve documents from a collection; i.e. query a collection
for documents. MongoDB provides the following methods to read documents
from a collection:
• Syntax:
• [Link]()
• Example:
• [Link]()
• [Link] ( { rollno : 6001 } )
• [Link] ( { rollno : { $in: [ 6001 , 6003 ] } } )
22
MongoDB Update Operations
• Update operations modify existing documents in a collection. MongoDB
provides the following methods to update documents of a collection:
• Syntax:
• [Link]()
• [Link]()
• Example:
• [Link]({ rollno : 6002 } , {$set: {name : “Ajay” } } )
• [Link]( { rollno : { $gt : 6160 } } ,
{ $set {name : “Undefine” } } )
23
MongoDB Delete Operations
• Delete operations remove documents from a collection. MongoDB provides
the following methods to delete documents of a collection:
• Syntax:
• [Link]()
• [Link]()
• Example:
• [Link] ( { rollno : 6160 } )
• [Link] ( { rollno : 6160 } )
24
Download [Link] on Windows
• Download Link : [Link]
25
Download [Link] on Windows
26
Install npm package of mongodb
project_path > npm install mongodb
Package Details: [Link]
27
[Link]
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://[Link]:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'practiceDB';
28
[Link]
async function main() {
// Use connect method to connect to the server
await [Link]();
[Link]('Connected successfully to server');
const db = [Link](dbName);
const collection = [Link]('students');
// CRUD Operation Code
return 'done.';
}
main()
.then([Link])
.catch([Link])
.finally(() => [Link]());
29
MongoDB-NodeJS Insert Operations
• Insert operations add new documents to a collection. MongoDB provides the
following methods to insert documents into a collection:
• Syntax:
• [Link]()
• [Link]()
• Example:
• [Link] ( { rollno:6001 , name: “Umang” } )
• [Link] ([
{ rollno:6002 , “name”: “Dhaval” } ,
{ rollno:6003 , “name”: “Ajay” }
])
30
MongoDB-NodeJS Insert Operations
// insertOne() Operation Code
const insertResult = await [Link](
{ rollno: 6001 , name:“Umang" });
[Link]('Inserted documents =>', insertResult);
// insertMany() Operation Code
const insertResult = await [Link]([
{ rollno: 6002 , name:"Dhaval" },
{ rollno: 6003 , name:"Ajay" } ]);
[Link]('Inserted documents =>', insertResult);
31
MongoDB-NodeJS Find Operations
• Find operations retrieve documents from a collection; i.e. query a collection for
documents. MongoDB provides the following methods to retrieve documents
from a collection:
• Syntax:
• [Link]({}).toArray()
• Example:
• [Link]({}).toArray()
• [Link] ({“rollno”:6001}) .toArray()
• [Link] ( { “rollno” : { $in: [ 6001 , 6003 ] } } ) .toArray()
32
MongoDB-NodeJS Find Operations
// Read: find() Operation...
const findResult = await [Link]({}).toArray();
[Link]('Found documents =>', findResult);
33
MongoDB-NodeJS Query Operations
// Read: find() Operation...
const queryResult = await [Link]({rollno:6001}).toArray();
[Link]('Found documents =>', queryResult);
// Read: find() Operation...
const queryResult = await [Link](
{rollno:{$in:[6001,6003]}}).toArray();
[Link]('Found documents =>', queryResult);
34
MongoDB-NodeJS Sort Operation
// Sort() Operation...
const sortResult = await [Link]({}).sort( {rollno:1}
).toArray();
[Link](‘Sorted documents =>', sortResult);
35
MongoDB-NodeJS Update Operations
• Update operations modify existing documents in a collection. MongoDB
provides the following methods to update documents of a collection:
• Syntax:
• [Link]()
• [Link]()
• Example:
• [Link]({ rollno : 6001 } , {$set: {name : “ajay” } } )
• [Link]({ rollno : 6002 } , {$set: {name : “dipak” } } )
36
MongoDB-NodeJS Update Operations
// updateOne() Operation...
const updateResult = await [Link](
{ rollno: 6001 }, { $set: { name: "ajay" } });
[Link]('Updated documents =>', updateResult);
// updateMany() Operation...
const updateResult = await [Link](
{ rollno: 6002 }, { $set: { name: “dipak" } });
[Link]('Updated documents =>', updateResult);
37
MongoDB-NodeJS Delete Operations
• Delete operations remove documents from a collection. MongoDB provides
the following methods to delete documents of a collection:
• Syntax:
• [Link]()
• [Link]()
• Example:
• [Link] ( { rollno : 6001} )
• [Link] ( { rollno : 6002} )
38
MongoDB-NodeJS Delete Operations
// deleteOne() Operation...
const deleteResult = await [Link] (
{ rollno: 6001 });
[Link]('Deleted documents =>', deleteResult );
// deleteMany() Operation...
const deleteResult = await [Link] (
{ rollno: 6002 });
[Link]('Deleted documents =>', deleteResult );
39