FSD NOTES UNIT-3-1
FSD NOTES UNIT-3-1
NoSQL:
NoSQL, or “Not Only SQL,” is a database management system
(DBMS) designed to handle large volumes of unstructured and semi-
structured data.
Unlike traditional relational databases (RDBMS), NoSQL databases
provide flexibility, scalability, and high performance for modern
applications.
Need of NoSQL:
Why NoSQL is Needed?
1. Handling Big Data
Traditional relational databases struggle to handle large volumes
of data generated by applications such as social media, IoT, and
e-commerce.
NoSQL databases can store and manage massive amounts of
data efficiently.
2. Scalability
RDBMS: Typically scales vertically (adding more power to a
single server).
NoSQL: – NoSQL databases can handle large amounts of data
by distributing it across multiple servers (horizontal scaling). In
contrast, RDBMS usually requires upgrading a single powerful
server (vertical scaling), which is costly and limited.
3. Flexible Schema
RDBMS follows a strict table structure, which can be difficult to
modify.
NoSQL allows schema-less data storage, means NoSQL
databases do not have a fixed schema like RDBMS. You can
store data in various formats (JSON, key-value pairs,
documents, graphs) without defining a strict table structure. This
makes it easy to modify and adapt to changing data
requirements.
4. High Performance:
NoSQL databases are optimized for fast read and write
operations, making them suitable for applications that need
real-time data access, such as social media platforms, gaming,
and big data applications.
MongoDB:
It is developed and supported by a company named 10gen which is now known as
MongoDB Inc.
MongoDB is a document-oriented NoSQL database system that provides high scalability,
flexibility, and performance.
Unlike standard relational databases, MongoDB stores data in a JSON document structure
form.
This makes it easy to operate with dynamic and unstructured data and MongoDB is an open-
source and cross-platform database System.
Database
Database is a container for collections.
Each database gets its own set of files.
A single MongoDB server can has multiple databases.
Collection
Collection is a group of documents.
Collection is equivalent to RDBMS table.
A collection consist inside a single database.
Collections do not enforce a schema.
A Collection can have different fields within a Documents.
Databases Databases
Tables Collections
Rows Documents
Columns Fields
Collection
Consider a student databse: { "_id": 1,
"name": "Anitha",
SQL "address": "HNK" Document1
}
Rolln
name Address {
o
"_id": 2,
1 Anitha HNK "name": "Sunitha",
2 Sunitha WGL "address": "WGL"
3 Pranitha KZP }
Datatypes in MongoDB: {
"_id": 3,
"name": "Pranitha",
"address": "KZP"
}
Integer: This datatype is used to store the numerical values.
Boolean: This datatype is used for implementing the Boolean values i.e true or false.
Double: This datatype is used for storing floating point data.
String: This is most commonly used datatype used for storing the string values.
Arrays: For storing an array or list of multiple values in one key ,this datatype is used.
Null: For storing null values this datatype is used.
Date: This datatype is used to store current date or time.We can also create our own date or
time object.
Object: The object is implemented for embedded documents.
Symbol: This datatype is similar to string datatype.This datatype is used to store specific
symbol type.
Binary: In order to store binary data we need to use this datatype.
Regular expression: This datatype is used to store regular expression.
CRUD operations
Create Operation:
a) Database Creation: Databases are created when you insert data into them. You can create
or switch to a database using the following command:
Syntax:
use <database_name>
Example: use Vaagdevi
switched to db Vaagdevi
Vaagdevi>
b) Show dbs: To see all available databases.
test> show dbs
config 72.00 KiB
grid 89.48 MiB
gridfs 89.46 MiB
local 72.00 KiB
Create or insert operations add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.
MongoDB provides the following methods to insert documents into a collection:
db.collection.insertOne()
db.collection.insertMany()
a)Creating collection
After creating database now we create a collection to store documents.
syntax:
db.createCollection("your_collection_name")
Note:
In MongoDB, collections are usually created automatically when you insert the first
document into them.
b) insertOne() function is used to store single data in the specified collection. And in the
curly braces {} we store our data or a document.
Syntax:
db.collection_name.insertOne({..})
Example:
db.employee.insertOne({empid:1,name:"nelli sathish",designation:"it
employee",qualification:"m.tech"})
{
acknowledged: true,
insertedIds: { '0': ObjectId('66e596036de17b79bbc73bf9') }
}
c) insertMany():To insert multiple documents at once.
db.employee.insertMany([{empid:2,name:"sravanthi jakkula",designation:"assistant
professor",qualification:"m.tech",phone:1234566778},{empid:3,name:"vasundhara
nam",designation:"assistant professor",qualification:"m.tech",address:"hyderabad"}])
{
acknowledged: true,
insertedIds:
{
'0': ObjectId('66e599596de17b79bbc73bfa'),
'1': ObjectId('66e599596de17b79bbc73bfb')
}
}
d) Show collections: To see all available collecions in database.
Syntax:
test> show collections
Read Operations
Read operations retrieve documents from a collection; i.e. query a collection for documents.
Update Operations
Update operations modify existing documents in a collection. MongoDB provides the
following methods to update documents of a collection:
db.collection.updateOne()-Updates a single document that matches the query.
db.collection.updateMany()– Updates multiple documents that match the query.
db.collection.replaceOne() – Replaces a single document with a new one
updateOne():
Example:
db.student.updateOne({name:"prashanthi"},{$set:{"fathername":"rammallu"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Find():db.student.find()
[
{
_id: ObjectId('67d1a4a7bd48f9f1dbb71236'),
rollno: 123,
name: 'Anitha'
},
{
_id: ObjectId('67d851da5f5f5daed5b71238'),
name: 'prashanthi',
fathername: 'rammallu',
mailid: '[email protected]'
}
]
updateMany:
Example:
vaagdevi> db.student.find();
[
{
_id: ObjectId('67d1a9a0bd48f9f1dbb71237'),
rollno: 123,
name: 'Anitha',
age: 20,
branch: 'ece',
Mobileno: 123456
},
{
_id: ObjectId('67d850e05f5f5daed5b71236'),
name: 'Pranitha',
branch: 'ECE'
},
{
_id: ObjectId('67d851da5f5f5daed5b71237'),
name: 'Pranitha',
branch: 'ECE'
},
{
_id: ObjectId('67d851da5f5f5daed5b71238'),
name: 'prashanthi',
fathername: 'rammallu',
mailid: '[email protected]'
},
{
_id: ObjectId('67db61608e3f40f738b71236'),
name: 'Ranjith',
branch: 'cse'
},
{
_id: ObjectId('67db61608e3f40f738b71237'),
name: 'Rama',
branch: 'cse'
}
]
vaagdevi> db.student.updateMany({branch:"cse"},{$set:{branch:"ece"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
vaagdevi> db.student.find();
[
{
_id: ObjectId('67d1a9a0bd48f9f1dbb71237'),
rollno: 123,
name: 'Anitha',
age: 20,
branch: 'ece',
Mobileno: 123456
},
{
_id: ObjectId('67d850e05f5f5daed5b71236'),
name: 'Pranitha',
branch: 'ECE'
},
{
_id: ObjectId('67d851da5f5f5daed5b71237'),
name: 'Pranitha',
branch: 'ECE'
},
{
_id: ObjectId('67d851da5f5f5daed5b71238'),
name: 'prashanthi',
fathername: 'rammallu',
mailid: '[email protected]'
},
{
_id: ObjectId('67db61608e3f40f738b71236'),
name: 'Ranjith',
branch: 'ece' //updated
},
{
_id: ObjectId('67db61608e3f40f738b71237'),
name: 'Rama',
branch: 'ece' //updated
}
]
Delete Operation:
}
]
Grants read and write access to a - Read and write data (insert,
readWrite
database. update, delete) in collections.
Remove users:
For removing the user , the db.dropUser() method is used.
Syntax:
db.dropUser(username)
Example
db.dropUser("pranitha")
{ ok: 1 }
Configuring access control:
Securing our database is very important to protect our data.
MongoDB, provides robust authentication mechanisms and role-based access control
(RBAC) features to secure data and manage user privileges effectively.
db.createUser({
user: "swapna",
pwd: "123456",
roles: [ { role: " readWriteAnyDatabase ", db: "admin" }]})
The readWriteAnyDatabase role grants full access across all databases.
In mongodb shell we can use this user to administer the database.
Managing Collections:
After creating database we must create collection inside that database.We can perform
various operations such as insert ,delete,update on this collection.These operations are called
CRUD opertions.
Week-6 Program
Step5: Finally use connect method to get connect with the database
client.connect();
week-7 programs
The db object:
The db objectis created for connecting to the database in MongoDB.
Methods of db object:
Method Purpose
collection(name) Access a collection in the database
createCollection(name,
options)
Create a new collection
dropCollection(name) Delete a collection from the database
listCollections(filter,
options)
List all collections in the database
Execute a database command (e.g.,
command(command)
stats)
dropDatabase() Delete the entire database
getCollection(name) Get a collection (alias to collection())
// Create a collection
await db.createCollection('users');
// Insert a document
const users = db.collection('users');
await users.insertOne({ name: 'John', age: 28 });
// Query documents
const user = await users.findOne({ name: 'John' });
console.log(user);
// List collections
const collections = await db.listCollections().toArray();
console.log(collections);
await client.close();
}
run();