0% found this document useful (0 votes)
27 views47 pages

UNIT-3( MONGO DB)

Uploaded by

Jaya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views47 pages

UNIT-3( MONGO DB)

Uploaded by

Jaya Prakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

UNIT-3 (MONGO DB)

• Need of NoSQL, Understanding MongoDB, MongoDB Data


Types, Planning Your Data Model, Building the MongoDB
Environment, Administering User Accounts, Configuring Access
Control, Administering Databases, Managing Collections, Adding
the MongoDB Driver to Node.js, Connecting to MongoDB from
Node.js, Understanding the Objects Used in the MongoDB
Node.js Driver, Accessing and Manipulating Databases, Accessing
and Manipulating Collections
Understanding NoSQL and MongoDB
• At the core of most large-scale web applications and services is a high-
performance data storage solution.
• The backend data store is responsible for storing everything from user account
information to shopping cart items to blog and comment data.
• Good web applications must store and retrieve data with accuracy, speed, and
reliability.
• Therefore, the data storage mechanism you choose must perform at a level that
satisfies user demand.
• The three most common are direct file system storage in
• files,
• Relational databases,
• and NoSQL databases.
Why NoSQL ((Not Only SQL) )?
• Challenges of an RDBMS
• Scalability: Relational databases often exist on one server, making it challenging for organizations
to scale them based on the growing size of the database and the complexity of data items.
• Performance: A relational database may experience reduced performance when organizing and
querying through large databases with many complex items.
• Cost: Setting up an RDBMS can be expensive because you require specific software to operate the
relational database.
• Physical storage: Relational databases require a lot of physical memory since there might be many
rows and columns in each table.
• Data limitations: It restricts the type of information users can store in the relational database and
makes it more challenging to organize complex data sets that contain different information.
• Complexity: When the relational database contains too many rows and columns of data items, the
table can be more complex. It can make it more of a challenge for the user to retrieve specific
information since there is too much information.
Why NoSQL ((Not Only SQL) )?
• The concept of NoSQL (Not Only SQL) consists of technologies that provide storage and retrieval
without the tightly constrained models of traditional SQL relational databases.
• The motivation behind NoSQL is mainly simplified designs, horizontal scaling, and finer control of
the availability of data.
• NoSQL breaks away from the traditional structure of relational databases and allows developers to
implement models in ways that more closely fit the data flow needs of their systems.
• There are several different NoSQL technologies, such as HBase’s column structure, Redis’s
key/value structure, and Neo4j’s graph structure.
• However, MongoDB and the document model were chosen because of great flexibility and
scalability when it comes to implementing backend storage for web applications and services.
• Also MongoDB is one of the most popular and well supported NoSQL databases currently
available.
Understanding MongoDB
Understanding MongoDB
• MongoDB is a NoSQL database based on a document model where data objects are stored as
separate documents inside a collection.
• The motivation of the MongoDB language is to implement a data store that provides high
performance, high availability, and automatic scaling.
• 1.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 MongoDB
• 2.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.
• In MongoDB, documents can contain embedded subdocuments, thus providing a much
closer inherent data model to your applications.
• In fact, 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.
Understanding MongoDB
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"}
}
Notice that the document structure contains fields/properties that are strings, integers, arrays,
and objects, just like a JavaScript object.
Understanding MongoDB
Understanding MongoDB
Understanding MongoDB
•Applications:
•Content Management Systems (CMS)

•E-commerce Applications

•Real-time Analytics

•Social Media Platforms

•Mobile Applications

•Internet of Things (IoT)

•Gaming Applications

•Healthcare Applications

•Financial Services
MongoDB Data Types
• The BSON data format provides several different types that are
used when storing the JavaScript objects to binary form.
• It is important to understand these types because you can actually
query MongoDB to find objects that have a specific property that
has a value of a certain type.
• For example, you can look for documents in a database whose
timestamp value is a String object or query for ones whose
timestamp is a Date object.
• MongoDB assigns each of the data types an integer ID number
from 1 to 255 that is used when querying by type.
MongoDB data types and corresponding ID number
Type Number
Double 1
String 2
Object 3
Array 4
Binary data 5
Object id 7
Boolean 8
Date 9
Null 10
Regular Expression 11
JavaScript 13
MongoDB data types
• When comparing values of different BSON types, MongoDB uses the following comparison
order from lowest to highest:
• 1. Min Key (internal type)
• 2. Null
• 3. Numbers (32-bit integer, 64-bit integer, Double)
• 4. String
• 5. Object
• 6. Array
• 7. Binary Data
• 8. Object ID
• 9. Boolean
• 10. Date, Timestamp
• 11. Regular Expression
• 12. Max Key (internal type)
Planning Your Data Model
• Before you begin implementing a MongoDB database, you need to understand the nature of the data
being stored, how that data is going to get stored, and how it is going to be accessed.
• Understanding these concepts allows you to make determinations ahead of time and to structure the
data and your application for optimal performance.
• Specifically, you should ask yourself the following questions:
• What are the basic objects that my application will be using?
• What is the relationship between the different object types: one-to-one, one-to-many, or many-to-
many?
• How often will new objects be added to the database?
• How often will objects be deleted from the database?
• How often will objects be changed?
• How often will objects be accessed?
• How will objects be accessed: by ID, property values, comparisons, and so on?
How will groups of object types be accessed: by common ID, common property value, and so on?
Planning Your Data Model
1) Normalizing Data with Document References
2) Denormalizing Data with Embedded Documents.
3) Using Capped Collections
4) Understanding Atomic Write Operations
5) Considering Document Growth
6) Identifying Indexing, Sharding, and Replication Opportunities
7) Deciding on Data Life Cycles
Building the MongoDB Environment
• Installing MongoDB
• The first step in getting MongoDB implemented into your Node.js environment is installing the
MongoDB server.
• There is a version of MongoDB for each of the major platforms, including Linux, Windows, Solaris,
and OS X.
• There is also an enterprise version available for the Red Hat, SuSE, Ubuntu, and Amazon Linux
distributions.
• Before continuing, go to the MongoDB website at http://docs.mongodb.org/manual/installation/.
Follow the links and instructions to download and install MongoDB in your environment:
• As part of the installation and setup process, perform the following steps:
• 1. Download and extract the MongoDB files.
• 2. Add the <mongo_install_location>/bin to your system path.
• 3. Create a data files directory: <mongo_data_location>/data/db.
• 4. Start MongoDB using the following command from the console prompt:
mongod –dbpath <mongo_data_location>/data/db
Installing MongoDB
Installing MongoDB
Installing MongoDB
Installing MongoDB
Installing MongoDB
Accessing MongoDB from the Shell Client
• Once you have installed, configured, and started MongoDB, you can access it through the MongoDB shell.
• The MongoDB shell is an interactive shell provided with MongoDB that allows you to access, configure, and
administer MongoDB databases, users, and much more. You use the shell for everything from setting up user
accounts to creating databases to querying the contents of the database.
• To start the MongoDB shell, first make sure that mongod is running, and then run the mongod command, then
execute the mongosh command from the console prompt.
• Current Mongosh Log ID: 66f252c9808c7f3e6bc73bf7
•Connecting to:
mongodb://127.0.0.1:27017/?
directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.1
•Using MongoDB: 8.0.0
•Using Mongosh: 2.3.1
• For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/
• ------
•------
•test>
Understanding MongoDB Shell commands
• help <option>: Displays syntax help for MongoDB shell commands. The
option argument allows you to specify an area where you want help.
• ■ use <database>: Changes the current database handle. Database
operations are processed on the current database handle.
• ■ db.help: Displays help options for the database methods.
• ■ show <option>: Shows a list based on the option argument. The value
of option can be:
• ■ dbs: Displays a list of databases.
• ■ collections: Displays a list of collections for the current database.
• ■ profile: Displays the five most recent system.profile entries taking
more than 1 millisecond.
• ■ databases: Displays a list of all available databases.
• ■ roles: Displays a list of all roles for the current database, both built-
in and userdefined.
• ■ users: Displays a list of all users for that database.
• ■ exit: Exits the database.
MongoDB Shell vs MongoDB Server:
•MongoDB Server is responsible to store our data in database.

•MongoDB Shell is responsible to manage Server.

•By using this shell we can perform all required CRUD operations.

•C --->Create

•R --->Retrieve

•U --->Update

•D --->Delete
MongoDB Shell vs MongoDB Server:
•MongoDB Server can be either local or remote (MongoDB ATLAS) .
•To Launch/Start MongoDB Server --->mongod command
•To Launch/Start MongoDB Shell --->mongosh Command

•By default, MongoDB listens for connections from clients on port 27017 , and stores
data in the /data/db directory.
•To Check Server Version: mongod –version

•To Check Shell Version: mongosh –version To

Check Documentation: db.help()

•To know current database: db.getName()


MongoDB
• MongoDB Admin will use these default databases.
• > show dbs
• admin 0.000GB config 0.000GB local 0.000GB

• 1. admin:
admin database is used to store user authentication and authorization information .
• 2. config:
To store configuration information of mongodb server.
• 3. local:
local database can be used by admin while performing replication process.
Creation of Database and Collection
• Database won't be created at the begining and it will be created dynamically.
• Whenever we are creating collection or inserting document then database will be
• created dynamically.
• test> show dbs
• admin 0.000GB
• config 0.000GB
• local 0.000GB
• test> use MYDB1
• switched to MYDB1
• MYDB1> show dbs
• admin 0.000GB
• config 0.000GB
• local 0.000GB
How to create collection
MYDB1> db.createCollection("students")
{ ok: 1 }

MYDB1> show dbs


MYDB1 8.00 KiB
admin 40.00 KiB
config 108.00 KiB
local 72.00 KiB
How to drop database?

• db.dropDatabase() - current database will be deleted.


• Note: db.getName() to know current database.
•db.students.deleteOne({rollno:111})- to delete one document in a collection
•{ acknowledged: true, deletedCount: 1 }
Basic CRUD Operations
• C--->Create|Insert document
• How to insert document into the collection?
• db.students.insertOne({"rollno":501 , "name":"cse1"})- To insert single
document.

• db.collection.insertMany()- To insert multiple documents.


• db.collection.insertMany([{..},{..},{..},{..}])
• db.employees.insertMany([
{eno: 200, ename: "Sunny", esal: 1000, eaddr: "Mumbai"},
{eno: 300, ename: "Sunny", esal: 1000, eaddr: "Mumbai"}
])
Basic CRUD Operations
• Creating Document separately and inserting into collection
• var emp = {};
• emp.eno = 7777;
• emp.ename = "Bunny";
• emp.esal = 777777;
• emp.eaddr = "Hyderabad";
• db.employees.insertOne(emp)
• db.employees.insertMany([emp])
• //db.employees.insert(emp)
• //db.employees.insert([emp])
Basic CRUD Operations
• Inserting Documents from java script file:
• studentsdb --->database
• students--->collection
• students.js:
db.students.insertOne({name: “Karthick", rollno: 101, marks: 98 })
db.students.insertOne({name: "Ravi", rollno: 102, marks: 99 })
db.students.insertOne({name: "Shiva", rollno: 103, marks: 100 })
db.students.insertOne({name: "Pavan", rollno: 104, marks: 80 })
• load("D:\students.js")
• > show collections
• > load("D:\students.js")
true
• > show collections
students
Basic CRUD Operations
• R--->Read / Retrieval Operation
• db.collection.find() --->To get all documents present in the given collection.
• db.collection.findOne() --->To get one document.
• eg: db.employees.find()
• > db.employees.find()
• { "_id" : ObjectId("5fe16d547789dad6d1278927"), "eno" : 100, "ename" : "Sunny", "esal" : 1000, "eaddr" : "Hyd" }
• { "_id" : ObjectId("5fe16da07789dad6d1278928"), "eno" : 200, "ename" : "Bunny", "esal" : 2000, "eaddr" : "Mumbai" }
• { "_id" : ObjectId("5fe16dc67789dad6d1278929"), "eno" : 300, "ename" : "Chinny", "esal" : 3000, "eaddr" : "Chennai" }
• { "_id" : ObjectId("5fe16ddb7789dad6d127892a"), "eno" : 400, "ename" : "Vinny", "esal" : 4000, "eaddr" : "Delhi" }

• >db.employees.find().pretty()
Basic CRUD Operations
• U-->Update Operation
• db.collection.updateOne()
• db.collection.updateMany()
• db.collection.replaceOne()
If the field is available then old value will be replaced with new value.
If the field is not already available then it will be created.
The update operation document must contain atomic operators.
>db.employees.updateOne({ename: "Vinny"},{$set: {esal:10000}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Note: If anything prefixed with $ symbol, then it is predefined word in
MongoDB
Basic CRUD Operations
• D -->Delete
• db.collection.deleteOne()
• db.collection.deleteMany()
• db.employees.deleteOne({ename:"Vinny"})
MONGO DB & NODE JS
• Install MongoDB Driver
• Let us try to access a MongoDB database with Node.js.
• To download and install the official MongoDB driver, open the Command
Terminal and execute the following:
• Download and install mongodb package:
>npm install mongodb
added 12 packages, and audited 30 packages in 2s
found 0 vulnerabilitiesdb
• Connecting to MongoDB from Node.js
• Node.js can use this module to manipulate MongoDB databases:
• var mongo = require('mongodb');
MONGO DB & NODE JS
• Implement CRUD operations on the given dataset using MongoDB.
•C- CREATE
•R- READ / RETRIVE
•U- UPDATE
• D- DELETE
// Connect to database and close the database connection
// Connect to database and close the database connection

const { MongoClient } = require('mongodb')


// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')

// Connect to database
client.connect()
.then(() => {
console.log('Connected Successfully!')

//Close the database connection


console.log('Exiting..')
client.close()
})
.catch(error => console.log('Failed to connect!', error))
To insert one document
// to insert one document
const { MongoClient } = require('mongodb')

// Create Instance of MongoClient for mongodb


const client = new MongoClient('mongodb://localhost:27017')

// Insert to database
client.db('MYDB').collection('students').insertOne({
name: 'cse1',
email: '[email protected]'
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
To find one document
//to find one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')

// Insert to database
client.db('MYDB').collection('students')
.findOne({name:'cse1'})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
To update one document
//to update one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')
// Insert to database
client.db('MYDB').collection('students')
.updateOne({ name: 'cse1' },
{
$set:
{ email: '[email protected]' }
})
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
To delete one document
//to delete one document
const { MongoClient } = require('mongodb')
// Create Instance of MongoClient for mongodb
const client = new MongoClient('mongodb://localhost:27017')

// Insert to database
client.db('MYDB').collection('students')
.deleteOne({ name: 'cse1' })
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => console.log(err))
CRUD Capped Collections
• What is capped collection?
• If size exceeds or maximum number of documents reached, then oldest entry
will be deleted automatically, such type of collections are called capped
collections.
• Capped collections are fixed-size circular collections that follow the insertion order
to support high performance for create, read, and delete operations.
• By circular, it means that when the fixed size allocated to the collection is
exhausted, it will start deleting the oldest document in the collection without
providing any explicit commands.
• Capped collections restrict updates to the documents if the update results in
increased document size. Since capped collections store documents in the order of
the disk storage, it ensures that the document size does not increase the size
allocated on the disk.
• Capped collections are best for storing log information, cache data, or any other
CRUD Capped Collections
• db.createCollection("employees")- normal
• db.createCollection(name)
• db.createCollection(name,options)
• //capped
• Max 1000 documents --->1001 document
• size: 3736578 bytes only --->if space completed
• //old documents will be deleted automatically.
• db.createCollection("employees",{capped: true, size: 3736578, max: 1000})
•  If capped is true means that if size exceeds or maximum number of documents
reached, then oldest entry will be deleted automatically.
CRUD Capped Collections
• 1.db.createCollection("employees") --->Normal Collection
• 2. db.createCollection("employees",{capped: true}) --->Invalid
• "errmsg" : "the 'size' field is required when 'capped' is true",
• 3. db.createCollection("employees",{capped: true, size: 365675})--->valid
• 4. db.createCollection("employees",{size: 365675}) --->invalid
• "errmsg" : "the 'capped' field needs to be true when either
the 'size' or 'max' fields are present“
• 5. db.createCollection("employees",{capped: true, size: 365675, max: 1000})---
>valid
• db.createCollection("employees",{capped: true, size: 365675, max: 1})

You might also like