0% found this document useful (0 votes)
6 views

Lecture - 1 MongoDB

Uploaded by

rais92730
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lecture - 1 MongoDB

Uploaded by

rais92730
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

LECTURE - 1

MongoDB
What is a Database?
An organized collection of data.
A method to manipulate and access the data.

Unorganized
Organized
Introduction To MongoDB

• MongoDB is an open-source, cross-platform, distributed document


database. MongoDB is developed by MongoDB Inc. and
categorized as a NoSQL database.
• Easy to use
• Designed to scale out
• Rich features
• High performance
MongoDB Editions
MongoDB has three editions: community server, enterprise server, and atlas.

1) MongoDB Community Server :


The MongoDB Community Edition is free and available on Windows, Linux, and
macOS.

2) MongoDB Enterprise Server :


MongoDB Enterprise Server is a commercial edition of MongoDB as a part of the
MongoDB Enterprise Advanced subscription.

3) MongoDB Atlas :
MongoDB Atlas is a global cloud database service. It is a database as a service that
allows
you to focus on building apps rather than spending time managing the databases.
MongoDB Structure
• MongoDB stores data in collections and documents.
• A collection is a group of MongoDB documents
• A document is a set of key-value pairs.
Collection : A container for documents (like a table).
Document : A JSON-like record within a collection (like a row).
Field : A key-value pair within a document (like a column).
MongoDB Basics
• Data formats
In MongoDB, you will often deal with JSON and BSON formats. Therefore, it’s important to fully understand
them.

• JSON
JSON stands for JavaScript Object Notation. JSON syntax is based on a subset of JavaScript ECMA-262 3rd
edition.
A JSON document is a collection of fields and values in a structured format. For example:
{
"first_name": "John",
"last_name": "Doe",
"age": 22,
"skills": ["Programming","Databases", "API"]
}
MongoDB Basics

• BSON
BSON stands for Binary JSON, which is a binary-coded
serialization of JSON-
like documents.
• Documents
MongoDB stores data records as BSON documents, which are
simply called
documents.
MongoDB Basics

• A document is a set of field-and-value pairs with the following


structure:
{
field_name1: value1,
field_name2: value2,
field_name3: value3,
...
}
In this syntax, the field names are strings and values can be
numbers, strings, objects, arrays, etc. For example:
MongoDB Basics

If you are familiar with a relational database management


system (RDBMS), you will find that a document is similar to a
row in a table, but it is much more expressive.

Field names have the following restrictions:


• MongoDB reserves the field_id and uses it to uniquely identify
the document.
• Field names cannot contain null characters.
• Top-level field names cannot start with the dollar sign ($)
character.
MongoDB Basics
• Collections
MongoDB stores documents in a collection. A collection is a group of
documents.

A collection is analogous to a table in an RDBMS.


MongoDB Basics
Unlike a table that has a fixed schema, a collection has a dynamic schema.
It means that a collection may contain documents that have any number of different “shapes”. For
example, you can store the following documents in the same collection:
{
title: "MongoDB Tutorial",
published_date: new Date('June 01, 2020')
}

{
title: "MongoDB Basics",
published_date: new Date('Jan 01, 2021'),
isbn": "978-4-7766-7944-8"
MongoDB Basics

Note that the second document has one more field than the first
one. In theory, you can have completely different fields for every
document.

A collection has a name e.g., books. The collection name cannot:


• contain the dollar sign ($)
• contain the null character (\0).
• be an empty string.
• begin with the system because MongoDB reserves system* for
internal collection names.
Databases
• MongoDB stores collections into a database. A single instance of MongoDB can
host multiple databases.

A database can be referenced by a name for example bookdb. The database names
cannot:
• Be an empty string ("").
• Contain any of these characters: /, \, ., “, *, <, >, :, |, ?, $, (a single space), or \0
(the null character).
• Exceed the maximum size which is 64 bytes.
MongoDB also has some reserved database names such as admin, local, and config
that you cannot use to create new databases.
Namespace

• A namespace is a concatenation of the database name with a


collection in that database. Namespaces allow you to fully
qualify collections.

• For example, if the collection name is books and database


name is bookdb, the namespace of the books collection
would be bookdb.books.
Mongo Shell
• The mongo shell is an interactive JavaScript interface to
MongoDB. The mongo shell allows you to manage data in
MongoDB as well as carry out administrative tasks.
• The mongo shell is similar to the mysql in MySQL, psql in
PostgreSQL, and SQL*Plus in Oracle Database.
• Note that the mongo shell that is included in the MongoDB
installation by default was deprecated in MongoDB v5.0. The
mongsh is the replacement of the legacy mongo shell.
Before using the mongo shell , you need to download and
install it .
Mongo Shell
• To start the mongo shell, you open the Terminal on macOS and Linux
or a Command Prompt on Windows and use the following command:
mongosh

• The mongo shell automatically connects to the MongoDB running on


the local server (localhost) with the default port (27017) . Therefore,
you need to ensure that the MongoDB server is up and listening on
this port before starting the mongo shell.
Note that you can use the mongo shell as a full-featured JavaScript
interpreter and as a MongoDB client.
Javascript Interpreter
• The mongo shell is a full-featured JavaScript interpreter so that you can execute any JavaScript code
like this:
Math.max(10,20,30);
30

• The mongo shell allows you to enter multiline commands. It will detect if the JavaScript statement is
complete when you press enter.

• If the statement is not complete, the mongo shell will allow you to type on the next line after the three
dots (...).
function add(a, b) {
... return a + b;
... }
add(10,20);
30
To clear the screen, you use the console.clear() like this: console.clear()
• Database
o Creating, connect, listing, droping
• CRUD
o Create - New collection
 Inserting data
o Read - How to read data
o Update data
o Delete data
Database And Collection

Create Database and Collection


• use database _ name
• db.createCollection("myCollection")
• show dbs
• show collections
Drop Database and Collection
• db.collection _ name.drop()
• db.dropDatabase()
MongoDB Client
• The mongo shell is a MongoDB client. By default, the mongo shell
connects to the test database on the MongoDB server and assigns
the database connection to the global variable called db.
• The db variable allows you to see the current database:
> db
test
Note that when you type a variable or an expression on the command
line, the mongo shell will evaluate it and returns the result.
Besides supporting JavaScript syntax, the mongosh shell provides you
with useful commands that easily interact with the MongoDB
database server .
MongoDB Client
For example, you can use the shows dbs command to list all the
databases on the server:
test> show dbs
admin 41 kB
config 73.7 kB
local 81.9 kB
The output shows three databases on the server.
To switch the current database to another , you use the use
<database> command. For example , the following command
switches the current database to the bookdb database:
test> use bookdb
switched to db bookdb
MongoDB Client

• The mongo shell now assigns bookdb to the db variable:


> db
Bookdb

• Now, you can access the books collection from the bookstore database via
the db variable like this:
> db.books
bookstore.books
Basic CRUD Operations
The following section shows you how to create (C), read (R),
update (U), and delete (D) a document. These operations are
often referred to as CRUD operations.

This section covers the basics of CRUD operations, including:


• Adding new documents to a collection
• Selecting documents
• Updating existing documents
• Removing documents from a collection
CRUD Operations

CREATE READ
insertOne() find()
insertMany() findOne()

UPDATE DELETE
updateOne() deleteOne()
updateMany() deleteMany()
Create
• To add a document to a collection, you use the insertOne() method of the
collection.
The following command adds a new document (or a new book) to the books
collection:
db.books.insertOne({
title: "MongoDB Tutorial",
published_year: 2020
})
Output :
{
"acknowledged" : true,
"insertedId" : ObjectId("5f2f39fb82f5c7bd6c9375a8")
}
Create
• Once you press enter, the mongo shell sends the command to the MongoDB
server.

• If the command is valid, MongoDB inserts the document and returns the result.
In this case, it returns an object that has two keys acknowledged and insertedId.

• The value of the insertedId is the value of the _id field in the document.

• When you add a document to a collection without specifying the _id field,
MongoDB automatically assigns a unique ObjectId value to the _id field and add
it to the document.

• MongoDB uses the _id field to uniquely identify the document in the collection.
Read
To select documents in a collection, you use the findOne()
method:
db.books.findOne()
Output :
{
_id: ObjectId("62143f34cca1c7af0ad1d126"),
title: 'MongoDB Tutorial',
published_year: 2020
}
Update

To update a single document, you use the updateOne() method.


The updateOne() method takes at least two arguments:
• The first argument identifies the document to update.
• The second argument represents the updates that you want to
make.
The following shows how to update the published_year of the
document whose title is "MongoDB Tutorial":
Output :
{
db.books.updateOne( acknowledged: true,
insertedId: null,
{ title: "MongoDB Tutorial"}, matchedCount: 1,
modifiedCount: 1,
{ $set: { published_year: 2019 }} upsertedCount: 0
}
)
Read
To format the output, you use the pretty() method like this:
db.books.find().pretty()
Output :
{
"_id" : ObjectId("5f2f3d8882f5c7bd6c9375ab"),
"title" : "MongoDB Tutorial",
"published_year" : 2020
}
How It Works.
The first argument identifies which document to update. In this case, it will
update the first document that has the title "MongoDB tutorial":
{title: "MongoDB Tutorial"}
The second argument is an object that specifies which fields in the
document to update:
{
$set: {
published_year: 2019
}
}
The $set is an operator that replaces a field value with a specified value .In
the example, it updates the published_year of the document to 2019.
Delete

• To delete a document from a collection, you use the deleteOne()


method. The deleteOne() method takes one argument that
identifies the document that you want to delete.
• The following example uses the deleteOne() method to delete a
document in the books collection:
db.books.deleteOne({title: "MongoDB Tutorial"});
Output:
{
"acknowledged": true,
"deletedCount": 1
}
Delete
The output shows that one document has been deleted
successfully via the deletedCount field.
To show all collections of the current database, you use the show
collections command:
show collections
Output:
Books

Currently, the bookdb database has one collection which is


books.
MongoDB Data Types
MongoDB stores data in BSON (Binary JSON) format.

BSON includes all JSON datatypes and adds more.

Choosing the correct datatype is essential for efficient storage and


querying.
MongoDB Data Types

1) Null : The null type is used to represent a null and a field that does not exist. For example
{

"isbn": null

2) Boolean : The boolean type has two values true and false. For example:

"best_seller": true

3) Number : By default, the mongo shell uses the 64-bit floating-point numbers. For example:

"price": 9.95,

“pages": 851

}
MongoDB Data Types

The NumberInt and NumberLong classes represent 4-byte and 8-byte integers respectively. For example:
{
"year": NumberInt("2020"),
"words": NumberLong("95403")
}
4) String : The string type represents any string of UTF-8 characters. For example:
{
"title": "MongDB Data Types"
}
5) Date : The date type stores dates as 64-bit integers that represents milliseconds since the Unix epoch
(January 1, 1970). It does not store the time zone. For example:
{
"updated_at": new Date()
MongoDB Data Types

6) Regular Expression : MongoDB allows you to store JavaScript regular expressions. For example:

"pattern": /\d+/

In this example, /\d+/ is a regular expression that matches one or more digits.

7) Array : The array type allows you to store a list of values of any type. The values do not have to be in the
same type, for example:

"title": "MongoDB Array",

“reviews": ["John", 3.5, "Jane", 5]

The good thing about arrays in the document is that MongoDB understands their structures and allows you to
carry operations on their elements.

For example, you can query all documents where 5 is an element of the reviews array. Also, you can create an
index on the reviews array to improve the query performance.
MongoDB Data Types

8) Embeded Document : A value of a document can be another document that is often referred to as an
embedded document.
The following example shows a book document that contains the author document as an embedded
document:
{
"title": "MongoDB Tutorial",
"pages": 945,
"author": {
"first_name": "John",
"last_name": "Doe"
}
}
In this example, the author document has its own key/value pairs including first_name and last_name.

You might also like