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
www.sites.google.com/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 : https://www.mongodb.com/what-is-mongodb/features
10
Download MongoDB for Windows
• Download Link-1 : https://www.mongodb.com/try/download/community
• Download Link-2 : http://www.mongodb.org/downloads.
11
Download MongoDB for Windows
12
Install MongoDB on Windows
• Installation Steps :
https://www.youtube.com/watch?v=n3onrnxcfio&list=PLFaWDe_XIA4pMorG
ET0zpP9qJHVO4aC6E&index=4
13
Download MongoDB Shell on Windows
• Download Link : https://www.mongodb.com/try/download/shell
14
Download MongoDB Shell on Windows
15
Install MongoDB Shell on Windows
• Installation Steps:
https://www.youtube.com/watch?v=oC6sKlhz0OE&t=234s
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: db.dropDatabase()
18
MongoDB Shell Collection Commands
(1) Create Collections
Syntax: db.createCollection(name)
Example: db.createCollection(“students”)
(2) Display Collection
Syntax: show collections
(3) Drop Collection
Syntax: db.collection_name.drop()
Example: db.students.drop()
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:
• db.collection.insertOne()
• db.collection.insertMany()
• Example:
• db.students.insertOne ( { rollno:6001 , name: “Umang” } )
• db.students.insertMany ([
{ 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:
• db.collection.find()
• Example:
• db.students.find()
• db.students.find ( { rollno : 6001 } )
• db.students.find ( { 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:
• db.collection.updateOne()
• db.collection.updateMany()
• Example:
• db.students.updateOne({ rollno : 6002 } , {$set: {name : “Ajay” } } )
• db.students.updateMany( { 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:
• db.collection.deleteOne()
• db.collection.deleteMany()
• Example:
• db.students.deleteOne ( { rollno : 6160 } )
• db.students.deleteMany ( { rollno : 6160 } )
24
Download Node.js on Windows
• Download Link : https://nodejs.org/en/
25
Download Node.js on Windows
26
Install npm package of mongodb
project_path > npm install mongodb
Package Details: https://www.npmjs.com/package/mongodb
27
Connect.js
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'practiceDB';
28
Connect.js
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('students');
// CRUD Operation Code
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
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:
• collection.insertOne()
• collection.insertMany()
• Example:
• collection.insertOne ( { rollno:6001 , name: “Umang” } )
• collection.insertMany ([
{ rollno:6002 , “name”: “Dhaval” } ,
{ rollno:6003 , “name”: “Ajay” }
])
30
MongoDB-NodeJS Insert Operations
// insertOne() Operation Code
const insertResult = await collection.insertOne(
{ rollno: 6001 , name:“Umang" });
console.log('Inserted documents =>', insertResult);
// insertMany() Operation Code
const insertResult = await collection.insertMany([
{ rollno: 6002 , name:"Dhaval" },
{ rollno: 6003 , name:"Ajay" } ]);
console.log('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:
• collection.find({}).toArray()
• Example:
• db.students.find({}).toArray()
• db.students.find ({“rollno”:6001}) .toArray()
• db.students.find ( { “rollno” : { $in: [ 6001 , 6003 ] } } ) .toArray()
32
MongoDB-NodeJS Find Operations
// Read: find() Operation...
const findResult = await collection.find({}).toArray();
console.log('Found documents =>', findResult);
33
MongoDB-NodeJS Query Operations
// Read: find() Operation...
const queryResult = await collection.find({rollno:6001}).toArray();
console.log('Found documents =>', queryResult);
// Read: find() Operation...
const queryResult = await collection.find(
{rollno:{$in:[6001,6003]}}).toArray();
console.log('Found documents =>', queryResult);
34
MongoDB-NodeJS Sort Operation
// Sort() Operation...
const sortResult = await collection.find({}).sort( {rollno:1}
).toArray();
console.log(‘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:
• collection.updateOne()
• collection.updateMany()
• Example:
• collection.updateOne({ rollno : 6001 } , {$set: {name : “ajay” } } )
• collection.updateMany({ rollno : 6002 } , {$set: {name : “dipak” } } )
36
MongoDB-NodeJS Update Operations
// updateOne() Operation...
const updateResult = await collection.updateOne(
{ rollno: 6001 }, { $set: { name: "ajay" } });
console.log('Updated documents =>', updateResult);
// updateMany() Operation...
const updateResult = await collection.updateMany(
{ rollno: 6002 }, { $set: { name: “dipak" } });
console.log('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:
• collection.deleteOne()
• collection.deleteMany()
• Example:
• collection.deleteOne ( { rollno : 6001} )
• collection.deleteMany ( { rollno : 6002} )
38
MongoDB-NodeJS Delete Operations
// deleteOne() Operation...
const deleteResult = await collection.deleteOne (
{ rollno: 6001 });
console.log('Deleted documents =>', deleteResult );
// deleteMany() Operation...
const deleteResult = await collection.deleteMany (
{ rollno: 6002 });
console.log('Deleted documents =>', deleteResult );
39