SlideShare a Scribd company logo

MongoDB.pdf

A
ArthyR3

This document helps to understand the concepts of mongodb. The document covers the CRUD operation and schema validation.

1 of 6
Download to read offline
Department of Information Technology
2023 – 2024 (ODD SEMESTER)
Year : III IT Course Code : IT2304
Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development
Course code
(as per NBA)
: 21ITC304 Regulation : R2021
UNIT V
Schema and Validation
 In MongoDB, schema and validation are crucial aspects of data management.
 Schema refers to the structure of data within a collection, defining the fields and their
data types.
 Validation, on the other hand, enforces rules to ensure that data inserted or updated
adheres to the defined schema.
Schema Definition
 MongoDB utilizes a flexible schema model, meaning that documents within a
collection do not necessarily share the same fields or data types.
 This flexibility allows for dynamic data structures and eases development.
 However, this flexibility can also lead to data inconsistencies and errors.
 To address this, MongoDB provides schema validation mechanisms that allow
defining rules for fields, such as data types, value ranges, and presence requirements.
 Validation rules are specified using JSON Schema, a vocabulary for describing the
structure of JSON data.
Validation Levels
 MongoDB offers two validation levels: strict and moderate.
o Strict validation: Enforces validation rules for all inserts and updates,
preventing invalid documents from being stored.
o Moderate validation: Applies validation rules only for new documents and
existing valid documents. Existing invalid documents remain unchanged.
Validation Implementation
 Schema validation can be implemented using various methods:
o Using db.createCollection(): During collection creation, the validator option
can be used to define validation rules.
o Using collMod command: For existing collections, the validator option can be
added to the collMod command to introduce validation rules.
o Using MongoDB Atlas: MongoDB Atlas provides a user interface for defining
and managing schema validation rules.
Benefits of Schema Validation
 Data Integrity: Enforces data consistency and prevents invalid or unexpected data
from being stored.
 Data Quality: Improves data quality by ensuring that data adheres to the defined
structure and constraints.
 Error Prevention: Reduces errors caused by invalid data, improving application
reliability and stability.
 Data Understanding: Provides a clear understanding of the expected data structure,
facilitating code development and maintenance.
Example: For Scheme
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const dbName = 'myDatabase';
const collectionName = 'users';
const schema = {
bsonType: 'object',
required: ['name', 'email'],
properties: {
name: {
bsonType: 'string',
minLength: 3,
maxLength: 50,
},
email: {
bsonType: 'string',
pattern: '^S+@[S+.]+$',
},
age: {
bsonType: 'int',
minimum: 18,
maximum: 120,
},
},
};
const createCollection = async () => {
const client = await MongoClient.connect(url);
const db = client.db(dbName);
await db.createCollection(collectionName, {
validator: {
$jsonSchema: schema,
},
});
console.log('Collection created successfully');
client.close();
};
createCollection();
Example: For Validation
{
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30
}
Insertion Success
{
"name": "Jane",
"email": invalid@email.com,
"age": 15
}
Insertion Failed – Age does not meet the constraint.
CRUD Operation in MongoDB with NodeJS
 CRUD operations, which stand for Create, Read, Update, and Delete, are fundamental
data manipulation actions in any database system. MongoDB, a NoSQL document-
oriented database, provides a straightforward and flexible approach to performing
CRUD operations using Node.js.
Creating a MongoDB Connection
 Before performing CRUD operations, you need to establish a connection to your
MongoDB instance.
 This can be done using the official MongoDB Node.js driver:
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const connect = async () => {
const client = await MongoClient.connect(url);
const db = client.db('myDatabase');
return db;
};
Create Operation:
 Use the insertOne or insertMany method to create new documents in a collection.
const express = require("express");
const app = express();
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.post('/add', (req, res) => {
const document = {name: req.body.name1, age: req.body.age1};
res.send(createDocument(db, collectionName, document))
});
async function createDocument(db, collectionName, document) {
const collection = db.collection(collectionName);
const result = await collection.insertOne(document);
console.log(`Document created with the _id: ${result.insertedId}`);
}
Read Operation:
 Use the find method to read data from a collection.
app.post('/read', (req, res) => {
const document = {name: req.body.name1};
res.send(findDocument(db, collectionName, document))
});
async function findDocuments(db, collectionName, query) {
const collection = db.collection(collectionName);
const result = await collection.find(query).toArray();
console.log('Found documents:', result);
}
Update Operation:
 Use the updateOne or updateMany method to update existing documents in a
collection.
app.post('/update', (req, res) => {
const document = {name: req.body.name1};
const update1 = {age: req.body.age1};
res.send(updateDocument(db, collectionName, document, update1))
});
async function updateDocument(db, collectionName, filter, update) {
const collection = db.collection(collectionName);
const result = await collection.updateOne(filter, { $set: update });
console.log(`Updated ${result.modifiedCount} document(s)`);
}
Delete Operation:
 Use the deleteOne or deleteMany method to delete documents from a collection.
app.post('/delete', (req, res) => {
const document = {name: req.body.name1};
res.send(deleteDocument(db, collectionName, document))
});
async function deleteDocument(db, collectionName, filter) {
const collection = db.collection(collectionName);
const result = await collection.deleteOne(filter);
console.log(`Deleted ${result.deletedCount} document(s)`);
}

Recommended

Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaMongoDB
 
How do i connect to that
How do i connect to thatHow do i connect to that
How do i connect to thatBecky Bertram
 
Document Validation in MongoDB 3.2
Document Validation in MongoDB 3.2Document Validation in MongoDB 3.2
Document Validation in MongoDB 3.2MongoDB
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101Will Button
 
06 asp.net session08
06 asp.net session0806 asp.net session08
06 asp.net session08Vivek chan
 

More Related Content

Similar to MongoDB.pdf

MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODEMSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODEannalakshmi35
 
Work with data in ASP.NET
Work with data in ASP.NETWork with data in ASP.NET
Work with data in ASP.NETPeter Gfader
 
Tutorial: Building Your First App with MongoDB Stitch
Tutorial: Building Your First App with MongoDB StitchTutorial: Building Your First App with MongoDB Stitch
Tutorial: Building Your First App with MongoDB StitchMongoDB
 
Novedades de MongoDB 3.6
Novedades de MongoDB 3.6Novedades de MongoDB 3.6
Novedades de MongoDB 3.6MongoDB
 
MongoDB Stitch Introduction
MongoDB Stitch IntroductionMongoDB Stitch Introduction
MongoDB Stitch IntroductionMongoDB
 
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDBMongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDBMongoDB
 
Murach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvcMurach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvcMahmoudOHassouna
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesAshishRathore72
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Sparkhound Inc.
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiNaveen Kumar Veligeti
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
 

Similar to MongoDB.pdf (20)

Knockout.js
Knockout.jsKnockout.js
Knockout.js
 
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODEMSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
MSWD:MERN STACK WEB DEVELOPMENT COURSE CODE
 
Work with data in ASP.NET
Work with data in ASP.NETWork with data in ASP.NET
Work with data in ASP.NET
 
Tutorial: Building Your First App with MongoDB Stitch
Tutorial: Building Your First App with MongoDB StitchTutorial: Building Your First App with MongoDB Stitch
Tutorial: Building Your First App with MongoDB Stitch
 
Novedades de MongoDB 3.6
Novedades de MongoDB 3.6Novedades de MongoDB 3.6
Novedades de MongoDB 3.6
 
MongoDB Stitch Introduction
MongoDB Stitch IntroductionMongoDB Stitch Introduction
MongoDB Stitch Introduction
 
unit 3.docx
unit 3.docxunit 3.docx
unit 3.docx
 
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDBMongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
MongoDB World 2018: Bumps and Breezes: Our Journey from RDBMS to MongoDB
 
Murach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvcMurach: How to validate data in asp.net core mvc
Murach: How to validate data in asp.net core mvc
 
Introduction to MongoDB and its best practices
Introduction to MongoDB and its best practicesIntroduction to MongoDB and its best practices
Introduction to MongoDB and its best practices
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
Optimizing Code Reusability for SharePoint using Linq to SharePoint & the MVP...
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
CHC 2009 - The Ccls Approach To Building M Pages
CHC 2009 - The Ccls Approach To Building M PagesCHC 2009 - The Ccls Approach To Building M Pages
CHC 2009 - The Ccls Approach To Building M Pages
 
Fundaments of Knockout js
Fundaments of Knockout jsFundaments of Knockout js
Fundaments of Knockout js
 

More from ArthyR3

OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfArthyR3
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdfArthyR3
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdfArthyR3
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdfArthyR3
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301ArthyR3
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit vArthyR3
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit vArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit ivArthyR3
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit iArthyR3
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)ArthyR3
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography WorkbookArthyR3
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network securityArthyR3
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bankArthyR3
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question keyArthyR3
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning materialArthyR3
 
Cyber forensics question bank
Cyber forensics   question bankCyber forensics   question bank
Cyber forensics question bankArthyR3
 

More from ArthyR3 (20)

OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
REACTJS.pdf
REACTJS.pdfREACTJS.pdf
REACTJS.pdf
 
ANGULARJS.pdf
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
 
JQUERY.pdf
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
 
CNS - Unit v
CNS - Unit vCNS - Unit v
CNS - Unit v
 
Cs8792 cns - unit v
Cs8792   cns - unit vCs8792   cns - unit v
Cs8792 cns - unit v
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit iv
Cs8792   cns - unit ivCs8792   cns - unit iv
Cs8792 cns - unit iv
 
Cs8792 cns - unit i
Cs8792   cns - unit iCs8792   cns - unit i
Cs8792 cns - unit i
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Cs8792 cns - Public key cryptosystem (Unit III)
Cs8792   cns - Public key cryptosystem (Unit III)Cs8792   cns - Public key cryptosystem (Unit III)
Cs8792 cns - Public key cryptosystem (Unit III)
 
Cryptography Workbook
Cryptography WorkbookCryptography Workbook
Cryptography Workbook
 
Cns
CnsCns
Cns
 
Cs6701 cryptography and network security
Cs6701 cryptography and network securityCs6701 cryptography and network security
Cs6701 cryptography and network security
 
Compiler question bank
Compiler question bankCompiler question bank
Compiler question bank
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Cyber forensics question bank
Cyber forensics   question bankCyber forensics   question bank
Cyber forensics question bank
 

Recently uploaded

Nexus - Final Day 12th February 2024.pptx
Nexus - Final Day 12th February 2024.pptxNexus - Final Day 12th February 2024.pptx
Nexus - Final Day 12th February 2024.pptxRohanAgarwal340656
 
Laser And its Application's - Engineering Physics
Laser And its Application's - Engineering PhysicsLaser And its Application's - Engineering Physics
Laser And its Application's - Engineering PhysicsPurva Nikam
 
Integrity Constraints in Database Management System.pptx
Integrity Constraints in Database Management System.pptxIntegrity Constraints in Database Management System.pptx
Integrity Constraints in Database Management System.pptxPallaviPatil905338
 
Paper Machine Troubleshooting manual for paper makers
Paper Machine Troubleshooting manual for paper makersPaper Machine Troubleshooting manual for paper makers
Paper Machine Troubleshooting manual for paper makersNoman khan
 
fat and edible oil processsing.ppt, refining
fat and edible oil processsing.ppt, refiningfat and edible oil processsing.ppt, refining
fat and edible oil processsing.ppt, refiningteddymebratie
 
B111_FTS_2011.06.01 Fuel Tank Safety.pdf
B111_FTS_2011.06.01 Fuel Tank Safety.pdfB111_FTS_2011.06.01 Fuel Tank Safety.pdf
B111_FTS_2011.06.01 Fuel Tank Safety.pdfKhoiTruong19
 
Forged Fitting Socket Welding Standard- ASME-B16.11-2001.pdf
Forged Fitting Socket Welding Standard- ASME-B16.11-2001.pdfForged Fitting Socket Welding Standard- ASME-B16.11-2001.pdf
Forged Fitting Socket Welding Standard- ASME-B16.11-2001.pdfVikasKumar11936
 
【文凭定制】坎特伯雷大学毕业证学历认证
【文凭定制】坎特伯雷大学毕业证学历认证【文凭定制】坎特伯雷大学毕业证学历认证
【文凭定制】坎特伯雷大学毕业证学历认证muvgemo
 
CCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERS
CCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERSCCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERS
CCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERSTamil949112
 
Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!
Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!
Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!Mathias Magdowski
 
Introduction and replication to DragonflyDB
Introduction and replication to DragonflyDBIntroduction and replication to DragonflyDB
Introduction and replication to DragonflyDBMarian Marinov
 
HB Self-Body characteristics UHV understanding
HB Self-Body characteristics UHV understandingHB Self-Body characteristics UHV understanding
HB Self-Body characteristics UHV understandingLeoRaju4
 
Introduction to the telecom tower industry
Introduction to the telecom tower industryIntroduction to the telecom tower industry
Introduction to the telecom tower industryssuserf5bbfd
 
Lesson2 Stoichiometry and mass balance.pdf
Lesson2 Stoichiometry and mass balance.pdfLesson2 Stoichiometry and mass balance.pdf
Lesson2 Stoichiometry and mass balance.pdff1002753214
 
Model Approved Food/ sanitary Grade Flow Meter
Model Approved Food/ sanitary Grade Flow MeterModel Approved Food/ sanitary Grade Flow Meter
Model Approved Food/ sanitary Grade Flow MeterManasMicrosystems
 
FSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdf
FSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdfFSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdf
FSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdfArnold Saludares
 
MedTech R&D - Tamer Emara - resume @2024
MedTech R&D - Tamer Emara - resume @2024MedTech R&D - Tamer Emara - resume @2024
MedTech R&D - Tamer Emara - resume @2024Tamer Emara
 
PM24_Oral_Presentation_Template_Guidelines.pptx
PM24_Oral_Presentation_Template_Guidelines.pptxPM24_Oral_Presentation_Template_Guidelines.pptx
PM24_Oral_Presentation_Template_Guidelines.pptxnissamant
 

Recently uploaded (20)

Nexus - Final Day 12th February 2024.pptx
Nexus - Final Day 12th February 2024.pptxNexus - Final Day 12th February 2024.pptx
Nexus - Final Day 12th February 2024.pptx
 
Laser And its Application's - Engineering Physics
Laser And its Application's - Engineering PhysicsLaser And its Application's - Engineering Physics
Laser And its Application's - Engineering Physics
 
Présentation IIRB 2024 Prévibest T. Leborgne
Présentation IIRB 2024 Prévibest T. LeborgnePrésentation IIRB 2024 Prévibest T. Leborgne
Présentation IIRB 2024 Prévibest T. Leborgne
 
Integrity Constraints in Database Management System.pptx
Integrity Constraints in Database Management System.pptxIntegrity Constraints in Database Management System.pptx
Integrity Constraints in Database Management System.pptx
 
Paper Machine Troubleshooting manual for paper makers
Paper Machine Troubleshooting manual for paper makersPaper Machine Troubleshooting manual for paper makers
Paper Machine Troubleshooting manual for paper makers
 
Présentation IIRB 2024 M.Campoverde R.Duval
Présentation IIRB 2024 M.Campoverde R.DuvalPrésentation IIRB 2024 M.Campoverde R.Duval
Présentation IIRB 2024 M.Campoverde R.Duval
 
fat and edible oil processsing.ppt, refining
fat and edible oil processsing.ppt, refiningfat and edible oil processsing.ppt, refining
fat and edible oil processsing.ppt, refining
 
B111_FTS_2011.06.01 Fuel Tank Safety.pdf
B111_FTS_2011.06.01 Fuel Tank Safety.pdfB111_FTS_2011.06.01 Fuel Tank Safety.pdf
B111_FTS_2011.06.01 Fuel Tank Safety.pdf
 
Forged Fitting Socket Welding Standard- ASME-B16.11-2001.pdf
Forged Fitting Socket Welding Standard- ASME-B16.11-2001.pdfForged Fitting Socket Welding Standard- ASME-B16.11-2001.pdf
Forged Fitting Socket Welding Standard- ASME-B16.11-2001.pdf
 
【文凭定制】坎特伯雷大学毕业证学历认证
【文凭定制】坎特伯雷大学毕业证学历认证【文凭定制】坎特伯雷大学毕业证学历认证
【文凭定制】坎特伯雷大学毕业证学历认证
 
CCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERS
CCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERSCCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERS
CCW332-DIGITAL MARKETING QUESTION BANK WITH ANSWERS
 
Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!
Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!
Robust, Precise, Fast - Chose Two for Radiated EMC Measurements!
 
Introduction and replication to DragonflyDB
Introduction and replication to DragonflyDBIntroduction and replication to DragonflyDB
Introduction and replication to DragonflyDB
 
HB Self-Body characteristics UHV understanding
HB Self-Body characteristics UHV understandingHB Self-Body characteristics UHV understanding
HB Self-Body characteristics UHV understanding
 
Introduction to the telecom tower industry
Introduction to the telecom tower industryIntroduction to the telecom tower industry
Introduction to the telecom tower industry
 
Lesson2 Stoichiometry and mass balance.pdf
Lesson2 Stoichiometry and mass balance.pdfLesson2 Stoichiometry and mass balance.pdf
Lesson2 Stoichiometry and mass balance.pdf
 
Model Approved Food/ sanitary Grade Flow Meter
Model Approved Food/ sanitary Grade Flow MeterModel Approved Food/ sanitary Grade Flow Meter
Model Approved Food/ sanitary Grade Flow Meter
 
FSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdf
FSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdfFSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdf
FSMR - FIRE SAFETY MAINTENANCE REPORT FORM.pdf
 
MedTech R&D - Tamer Emara - resume @2024
MedTech R&D - Tamer Emara - resume @2024MedTech R&D - Tamer Emara - resume @2024
MedTech R&D - Tamer Emara - resume @2024
 
PM24_Oral_Presentation_Template_Guidelines.pptx
PM24_Oral_Presentation_Template_Guidelines.pptxPM24_Oral_Presentation_Template_Guidelines.pptx
PM24_Oral_Presentation_Template_Guidelines.pptx
 

MongoDB.pdf

  • 1. Department of Information Technology 2023 – 2024 (ODD SEMESTER) Year : III IT Course Code : IT2304 Faculty Name : Dr. R. Arthy, AP/IT Course Name : Full Stack Web Development Course code (as per NBA) : 21ITC304 Regulation : R2021 UNIT V Schema and Validation  In MongoDB, schema and validation are crucial aspects of data management.  Schema refers to the structure of data within a collection, defining the fields and their data types.  Validation, on the other hand, enforces rules to ensure that data inserted or updated adheres to the defined schema. Schema Definition  MongoDB utilizes a flexible schema model, meaning that documents within a collection do not necessarily share the same fields or data types.  This flexibility allows for dynamic data structures and eases development.  However, this flexibility can also lead to data inconsistencies and errors.  To address this, MongoDB provides schema validation mechanisms that allow defining rules for fields, such as data types, value ranges, and presence requirements.  Validation rules are specified using JSON Schema, a vocabulary for describing the structure of JSON data. Validation Levels  MongoDB offers two validation levels: strict and moderate. o Strict validation: Enforces validation rules for all inserts and updates, preventing invalid documents from being stored.
  • 2. o Moderate validation: Applies validation rules only for new documents and existing valid documents. Existing invalid documents remain unchanged. Validation Implementation  Schema validation can be implemented using various methods: o Using db.createCollection(): During collection creation, the validator option can be used to define validation rules. o Using collMod command: For existing collections, the validator option can be added to the collMod command to introduce validation rules. o Using MongoDB Atlas: MongoDB Atlas provides a user interface for defining and managing schema validation rules. Benefits of Schema Validation  Data Integrity: Enforces data consistency and prevents invalid or unexpected data from being stored.  Data Quality: Improves data quality by ensuring that data adheres to the defined structure and constraints.  Error Prevention: Reduces errors caused by invalid data, improving application reliability and stability.  Data Understanding: Provides a clear understanding of the expected data structure, facilitating code development and maintenance. Example: For Scheme const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const dbName = 'myDatabase'; const collectionName = 'users'; const schema = { bsonType: 'object', required: ['name', 'email'], properties: { name: { bsonType: 'string', minLength: 3, maxLength: 50,
  • 3. }, email: { bsonType: 'string', pattern: '^S+@[S+.]+$', }, age: { bsonType: 'int', minimum: 18, maximum: 120, }, }, }; const createCollection = async () => { const client = await MongoClient.connect(url); const db = client.db(dbName); await db.createCollection(collectionName, { validator: { $jsonSchema: schema, }, }); console.log('Collection created successfully'); client.close(); }; createCollection(); Example: For Validation { "name": "John Doe", "email": "johndoe@example.com", "age": 30
  • 4. } Insertion Success { "name": "Jane", "email": invalid@email.com, "age": 15 } Insertion Failed – Age does not meet the constraint. CRUD Operation in MongoDB with NodeJS  CRUD operations, which stand for Create, Read, Update, and Delete, are fundamental data manipulation actions in any database system. MongoDB, a NoSQL document- oriented database, provides a straightforward and flexible approach to performing CRUD operations using Node.js. Creating a MongoDB Connection  Before performing CRUD operations, you need to establish a connection to your MongoDB instance.  This can be done using the official MongoDB Node.js driver: const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const connect = async () => { const client = await MongoClient.connect(url); const db = client.db('myDatabase'); return db; }; Create Operation:  Use the insertOne or insertMany method to create new documents in a collection.
  • 5. const express = require("express"); const app = express(); app.use(express.static('public')); app.use(express.urlencoded({ extended: true })); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); app.post('/add', (req, res) => { const document = {name: req.body.name1, age: req.body.age1}; res.send(createDocument(db, collectionName, document)) }); async function createDocument(db, collectionName, document) { const collection = db.collection(collectionName); const result = await collection.insertOne(document); console.log(`Document created with the _id: ${result.insertedId}`); } Read Operation:  Use the find method to read data from a collection. app.post('/read', (req, res) => { const document = {name: req.body.name1}; res.send(findDocument(db, collectionName, document)) }); async function findDocuments(db, collectionName, query) { const collection = db.collection(collectionName); const result = await collection.find(query).toArray(); console.log('Found documents:', result); }
  • 6. Update Operation:  Use the updateOne or updateMany method to update existing documents in a collection. app.post('/update', (req, res) => { const document = {name: req.body.name1}; const update1 = {age: req.body.age1}; res.send(updateDocument(db, collectionName, document, update1)) }); async function updateDocument(db, collectionName, filter, update) { const collection = db.collection(collectionName); const result = await collection.updateOne(filter, { $set: update }); console.log(`Updated ${result.modifiedCount} document(s)`); } Delete Operation:  Use the deleteOne or deleteMany method to delete documents from a collection. app.post('/delete', (req, res) => { const document = {name: req.body.name1}; res.send(deleteDocument(db, collectionName, document)) }); async function deleteDocument(db, collectionName, filter) { const collection = db.collection(collectionName); const result = await collection.deleteOne(filter); console.log(`Deleted ${result.deletedCount} document(s)`); }