0% found this document useful (0 votes)
3 views10 pages

Module 3 Mongodb

MongoDB is an open-source, non-relational NoSQL document-oriented data store designed to handle large volumes of unstructured data with high performance and flexibility. It features dynamic schemas, replication for high availability, sharding for horizontal scalability, and supports CRUD operations through a rich query language. Key components include databases, collections, and documents, with BSON format for data storage and various data types supported.

Uploaded by

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

Module 3 Mongodb

MongoDB is an open-source, non-relational NoSQL document-oriented data store designed to handle large volumes of unstructured data with high performance and flexibility. It features dynamic schemas, replication for high availability, sharding for horizontal scalability, and supports CRUD operations through a rich query language. Key components include databases, collections, and documents, with BSON format for data storage and various data types supported.

Uploaded by

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

Module 3

MongoDB

 WHAT IS MONGODB?
MongoDB is Cross-platform Open source Non-relational Distribute NoSQL Dacument-oriented
data store.

 WHY MONGODB?
Few of the major challenges with traditional RDBMS are dealing with large volumes of data,
rich variety data — particularly unstructured data, and meeting up to the scale needs of enterprise
data. The need is for database that can scale out or scale horizontally to meet the scale
requirements, has flexibility with respect schema, is fault tolerant, is consistent and partition
tolerant, and can be easily distributed over a multitude of nodes in a cluster.

JSON is extremely expressive. MongoDB actually does not use JSON but BSON is Binary
JSON. It is an open standard. It is used to store complex data structures.

 Features of MongoDB
 Document-oriented storage
 High performance
 Flexible schema
 High availability through replication
 Horizontal scalability via sharding
 Rich query language
 In-built aggregation framework
 Index support

 Creating or Generating a Unique Key


 Each JSON document should have a unique identifier.
 It is the _id key. It is similar to the primary key in relational
databases. This facilitates search for documents based on the
unique identifier.
 An index is automatically built on the unique identifier. It is your
choice to either provide unique values yourself or have the mongo
shell generate the same.
 Database
 It is a collection of collections. In other words, it is like a container for
collections.
 It gets created the first time that your collection makes a reference to it. This can
also be created on demand. Each database gets its own set of files on the file
system. A single MongoDB server can house several databases.
 Collection
 A collection is analogous to a table of RDBMS. A collection is created on
demand.
 It gets created the first time that you attempt to save a document that references
it. A collection exists within a single database.
 A collection holds several MongoDB documents. A collection does not
references a schema. This implies thatdocuments within a collection can have
different fields. Even if the documents within a collection have same fields, the
order of the fields can be different.
 Document
A document is analogous to a row/record/tuple in an RDBMS table.
A document has a dynamic schema: This implies that a document in a collection need
not necessarily have the same set of fields/key—value pair.

 Support for Dynamic Queries

 MongoDB has extensive support for dynamic queries. we have static data
and dynamic queries.
 Storing Binary Data
 mongogoDB provides GridFS to support the storage of binary data. It can
store up to 4 MB of data.
 This suffices for photographs (such as a profile picture) or small audio
clips, However, if one wishes to store movie clips, MongoDB has another
solution it stores the metadata (data about data along with the context
information) in a collection called “file”.
 It then breaks the data into small pieces called chunks and stores it in the
“chunks” collection. This process make easy scalability.
 Replication
 It provides data redundancy and high availability. It helps to recover from
hardware failure and service interruptions.
 In MongoDB, the replica set has a single primary and several secondaries.
 Each write request from the client is directed to the primary. The primary
logs all write requests into its Oplog (operations log).
 The Oplog is then used by the secondary replica members to synchronize
their Data.
 This way there is strict adherence to consistency. Refer Figure. The
clients usually read from the primary. However, the client can also
specify a read preference that will then direct the read operations to
the secondary.
 The process of SHARDING in mongodb.
Sharding is akin to horizontal scaling. It means that the large dataset is divided
and distributed over multiple servers or shards. Each shard is an independent
database and collectively they would constitute a logics database.
The prime advantages of sharding are as follows:

1. Sharding reduces the amount of data that each shard needs to store and
manage. For example, if
dataset was 1 TB in size and we were to distribute this over four shards, each
shard would house just 256 GB data. Refer Figure 6.4. As the cluster grows, the
amount of data that each shard will store and manage will decrease.

2. Sharding reduces the number of operations that each shard handles. For
example, if we were to insert data, the application needs to access only that shard
which houses that data.

 Updating Information In-Place


 MongoDB updates the information in-place. This implies chat it updates
the data wherever it is available.
 It does not allocate separate space and the indexes remain unaltered.
 MongoDB is all for lazy-writes. It writes to the disk once every second,
Reading and writing to disk slow operation as compared to reading and
writing from memory.
 The fewer the reads and writes that perform to the disk, the better is the
performance. write almost immediately to the disk. However, there is a
tradeoff. MongoDB makes no guarantee data will be stored safely on the
disk.

 MongoDB vs RDBMS
 Collection vs Table
 Document vs Row
 Field vs Column
 Embedded Document vs Join
 Dynamic Schema vs Fixed Schema

 Create Database
The syntax for creating database is as follows:
use DATABASE Name
To create a database by the name “myDB” the syntax is
use myDB;
switched to db myDB;
To confirm the existence of your database, type the command at the MongoDB shell:
db;
myDB
To get a list of all databases, type the below command:
> show dbs;
admin (empty)
flocal 0.078GB
test 0.078cB
>
Notice that the newly created database, “myDB” does not show up in the list above. The reason
is that
database needs to have at least one document to show up in the list
The default database in MongoDB is test. If one does not create any database, all collections are
by
stored in the test database.

 Drop Database
The syntax to drop database is as follows:
db.dropDatabase();
‘To drop the database, “myDB”, first ensure that you are currently placed in “myDB” database
and then
the db.dropDatabase() command to drop the database.

use myDB;
db.dropDarabase();

Confirm if the database “myDB” has been dropped.


db. dropDatabase() ;

“dropped : "myDB", “ok" : 1 }

If no database is selected, the default database “test” is dropped.

 Data Types and BSON Format

Type Example Description


String "name": "Alice" Text data
Number "age": 25 Integer, float
Boolean "status": true true or false
Date "dob": ISODate("2023-05-01") Date and time
Array "skills": ["C", "Java"] List of values
Object "address": {"city": "BLR"} Nested document
ObjectId _id: ObjectId("abc123...") Unique 12-byte document ID
Null "remarks": null Null value
Binary For storing binary data/files Binary large objects

 CRUD Operations
CRUD stands for the four basic operations that can be performed on data in a database:

 C – Create: Add new documents.

 R – Read: Retrieve documents.

 U – Update: Modify existing documents.

 D – Delete: Remove documents.


 Create: Used to insert new documents into a collection.

 insertOne(): Inserts a single document.

db.students.insertOne({name: "Asha", age: 22})

 insertMany(): Inserts multiple documents.

db.students.insertMany([{name: "Raj"}, {name: "Neha"}])

 Read: Used to retrieve documents from a collection.


 find(): Returns matching documents.

db.students.find()

 With filter conditions:

db.students.find({ age: { $gt: 21 } }) // Fetch students with age > 21

db.students.find({ name: "Asha" }) // Fetch student named Asha

db.students.find({age: {$gt: 20}})

 findOne(): Returns only the first match.


db.students.findOne({ name: "Raj" })

 Update: Used to modify existing documents.


 updateOne(): Updates the first matched document.

db.students.updateOne({name: "Raj"}, {$set: {age: 23}})

 updateMany(): Updates all matching documents.


db.students.updateMany(
{ course: "BDA" },
{ $set: { year: 2025 } }
)

 Delete: Used to remove documents from a collection.

 deleteOne(): Deletes the first matched document.


db.students.deleteOne({ name: "Ravi" })

 deleteMany(): Deletes all matching documents.


db.students.deleteMany({ course: "BDA" })
 Mongodb query language

CRUD (Create, Read Update, and Delete) operations in


MongoDB

Create — Creation of data is done using insert() or update() or


save() method.

Read —» Reading the data is performed using the find()


method.
Update —> Update to data is accomplished using the update()
method with UPSERT set to
Delete -> adocument is Deleted using the remove() method.

 Objective: To create a collection by the name “Person”. Let us


take a look at the collection list pl
to the creation of the new collection “Person”:

system. indexes
peta: is

Act: The statement to create the collection is


db.createCollection(“Person”)

 Save() Method

‘We cow explain the save() method. The save() method will
insert a new document if the document with specified _id does
not exist. However, if a document with the specified id exists, it
replaces the existing document with the new one.

Example : db.collection.save({
_id: ObjectId("60f6b2d4c2a1d2d1e4f8f123"),
name: "Raj",
age: 28
})

 Inserting Null Values


 MongoDB allows fields to have null as a value.
 It also allows documents to omit fields entirely.

db.students.insertOne({ name: "Ravi", age: null })

 Count, Limit, Sort, and Skip


Objective: To find the number of documents in the Students
collection.

Act:
db.Students.count()

Outcome:
5

Objective: To find the number of documents in the Students


collection wherein the Grade is VII.

Act:
db.Students.count({Grade:"VII"});

Outcome:
4

Objective: To retrieve the first 3 documents from the Students


collection wherein the Grade is VII.
Act:
db.Students.find({Grade:"VII"}).limit(3).pretty(Q);

Outcome:
PRINT FIRST THREE DOCUMENTS IN THE LIST

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy