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

Unit 6 Database Progrmming with Nodejs and MongoDB

Uploaded by

tecnoj522
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views47 pages

Unit 6 Database Progrmming with Nodejs and MongoDB

Uploaded by

tecnoj522
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 47

Unit 6

Database Programming With


Node JS and MongoDB

Compiled by:
Ms. Vaibhavi Parekh
Mongo DB
• MongoDB is a document database. It stores data in a
type of JSON format called BSON.
• A record in MongoDB is a document, which is a data
structure composed of key value pairs similar to the
structure of JSON objects.
• MongoDB is a document database and can be
installed locally or hosted in the cloud.
SQL vs Document Databases
• SQL databases are considered relational databases. They store
related data in separate tables. When data is needed, it is
queried from multiple tables to join the data back together.
• MongoDB is a document database which is often referred to as
a non-relational database. This does not mean that relational
data cannot be stored in document databases. It means that
relational data is stored differently. A better way to refer to it is
as a non-tabular database.
• MongoDB stores data in flexible documents. Instead of having
multiple tables you can simply keep all of your related data
together. This makes reading your data very fast.
• You can still have multiple groups of data too. In MongoDB,
instead of tables these are called collections.
Local vs Cloud Database
• MongoDB can be installed locally, which will allow you
to host your own MongoDB server on your hardware.
This requires you to manage your server, upgrades, and
any other maintenance.
• You can download and use the MongoDB open
source Community Server on your hardware for free.
• However, for this course we are going to use MongoDB
Atlas, a cloud database platform. This is much easier than
hosting your own local database.
• To be able to experiment with the code examples, you will
need access to a MongoDB database.
• Sign up for a free MongoDB Atlas account to get started.
Creating a Cluster
• After you have created your account, set up a free
"Shared Cluster" then choose your preferred cloud
provider and region.
• By default, MongoDB Atlas is completely locked down
and has no external access.
• You will need to set up a user and add your IP address to
the list of allowed IP addresses.
• Under "Database Access", create a new user and keep
track of the username and password.
• Next, under "Network Access", add your current IP
address to allow access from your computer.
Install MongoDB Shell (mongosh)

• There are many ways to connect to your MongoDB


database.
• We will start by using the MongoDB Shell, mongosh.
• Use the official instructions to install mongosh on
your operating system.
• To verify that it has been installed properly, open
your terminal and type:
Connect to the database
• To connect to your database, you will need your
database specific connection string.
• In the MongoDB Atlas dashboard, under "Databases",
click the "Connect" button for your Cluster.
• Next, choose "Connect with the MongoDB Shell".
• Copy your connection string.
• Paste your connection string into your terminal and
press enter.
• You will be prompted to enter your database user
password that you created earlier.
• You are now connected to the database!
A MongoDB Document
• Records in a MongoDB database are called documents,
and the field values may include numbers, strings,
booleans, arrays, or even nested documents.
{
title: "Post Title 1",
body: "Body of post.",
category: "News",
likes: 1,
tags: ["news", "events"],
date: Date()
}
Data Types
• In MongoDB, the documents are stores in BSON,
which is the binary encoded format of JSON and
using BSON we can make remote procedure calls in
MongoDB.

• BSON data format supports various data-types.


Below are the enlisted MongoDB data types:
String
• String: This is the most commonly used data type in
MongoDB to store data, BSON strings are of UTF-8. So,
the drivers for each programming language convert from
the string format of the language to UTF-8 while serializing
and de-serializing BSON. The string must be a valid UTF-
8. Example of string data type is as follows:
Integer
• Integer: In MongoDB, the integer data type is used to store
an integer value. We can store integer data type in two
forms 32 -bit signed integer and 64 – bit signed integer.
• Example shows storing age of students in data collection.
Double
• Double: The double data type is used to store the
floating-point values.
Boolean
• Boolean: The boolean data type is used to store either
true or false.
Null
• Null: The null data type is used to store the null value.
Array
• Array: The Array is the set of values. It can store the same
or different data types values in it. In MongoDB, the array
is created using square brackets([]).
Object
• Object: Object data type stores embedded documents.
Embedded documents are also known as nested
documents. Embedded document or nested documents are
those types of documents which contain a document inside
another document.
Object Id
• Object Id: Whenever we create a new document in the
collection MongoDB automatically creates a
unique object id for that document(if the document does
not have it). There is an _id field in MongoDB for each
document. The data which is stored in Id is of
hexadecimal format and the length of the id is 12 bytes
which consist:
• 4-bytes for Timestamp value.
• 5-bytes for Random values. i.e., 3-bytes for machine Id
and 2-bytes for process Id.
• 3- bytes for Counter
Object Id
• You can also create your own id field, but make sure that
the value of that id field must be unique.
Undefined
• Undefined: This data type stores the undefined
values.
Binary Data
• Binary Data: This datatype is used to store binary
data.
Date
• Date: Date data type stores date. It is a 64-bit integer
which represents the number of milliseconds. BSON data
type generally supports UTC datetime and it is signed. If
the value of the date data type is negative then it represents
the dates before 1970. There are various methods to return
date, it can be returned either as a string or as a date
object. Some method for the date:
• Date(): It returns the current date in string format.
• new Date(): Returns a date object. Uses the ISODate()
wrapper.
• new ISODate(): It also returns a date object. Uses the
ISODate() wrapper.
Date
Min Max Key
• Min & Max key: Min key compares the value of the
lowest BSON element and Max key compares the value
against the highest BSON element. Both are internal data
types.
Symbol
• Symbol: This data type similar to the string data type. It is
generally not supported by a mongo shell, but if the shell
gets a symbol from the database, then it converts this type
into a string type.
Regular Expression
• Regular Expression: This datatype is used to store
regular expressions.
JavaScript
• JavaScript: This datatype is used to store JavaScript
code into the document without the scope.
JavaScript WITH Scope
• JavaScript with Scope: This MongoDB data type store
JavaScript data with a scope. This data type is
deprecated in MongoDB 4.4.
Timestamp
• Timestamp: In MongoDB, this data type is used to store
a timestamp. It is useful when we modify our data to keep
a record and the value of this data type is 64-bit. The
value of the timestamp data type is always unique.
Decimal
• Decimal: This MongoDB data type store 128-bit decimal-
based floating-point value. This data type was introduced
in MongoDB version 3.4
What is ObjectId in MongoDB
• Every document in the collection has an “_id” field that is
used to uniquely identify the document in a particular
collection it acts as the primary key for the documents in
the collection. “_id” field can be used in any format and the
default format is ObjectId of the document.
• An ObjectID is a 12-byte Field Of BSON type
• The first 4 bytes representing the Unix Timestamp of the
document
• The next 3 bytes are the machine Id on which the
MongoDB server is running.
• The next 2 bytes are of process id
• The last Field is 3 bytes used for increment the objectid.
Format of Object ID

ObjectId(<hexadecimal>)

• ObjectId accepts one parameter which is optional


Hexadecimal ObjectId in String.
• We can give our own ObjectId to the document but it
must be unique.
• *db.<collectionname>.insertOne({"_id":"231231"})
Example
• Database : gfg
• Collection: student_gfg
Methods of Object Id
• str: Returns the hexadecimal string format of the
ObjectId
• ObjectId.getTimestamp() : It returns the timestamp
portion of the object as a Date.
• ObjectId.valueOf(): It return the hexadecimal format
of a given String Literal.
• ObjectId.toString(): This method returns ObjectId
in String format in javascript representation.
Creating Object Id
• To generate new ObjectId of particular document.
• newObjectId = ObjectId()

• Output:
• ObjectId(“5f92cbf10cf217478ba93561”)
Timestamp of the ObjectID
• It returns the timestamp information of the object as a
date in ISO format.
Converting ObjectId to string
• ObjectId can be converted into string format.
Install MongoDB On Windows
• To install MongoDB on Windows, first download the
latest release of MongoDB from
https://www.mongodb.com/download-center
Install MongoDB On Windows
Connectivity with nodejs
• Node.js and npm:Node.js is a JavaScript runtime for
building fast and scalable network applications, and it
comes with npm installed.
• MongoDB Node.js driver:To connect your application
with a database, you need a software component, also
known as a driver. MongoDB Node.js driver supports
database connection, authentication, CRUD operations,
and observations, among other features.
• MongoDB Atlas:You can create a database either locally
or in the cloud by using MongoDB Atlas, a fully
managed cloud database service.
• Initialize the Project
• First, create a project directory called “node-mongoDB”. Open your
terminal and execute the following command:
• mkdir node-mongoDB && cd node-mongoDB
• Once inside the directory, create a “package.json” file by running
the following command:
• npm init –y
• The “y” flag generates an npm package that uses the default values.
• In this project, we’ll use ECMAScript modules, which are
the standardized way to package JavaScript code. To enable
ECMAScript modules, add a new field to the “package.json” file:
• "type": "module“
• This will instruct Node.js to treat your JavaScript code as
ECMAScript modules instead of the default CommonJS modules.
Enabling ECMAScript modules will also allow us to use top-level
await. In short, this means that we can use the await keyword
outside of async functions.
Add MongoDB as a Dependency

• Next, install the MongoDB driver along with its


dependencies by running the following command:
• npm install mongodb
• The execution of the npm install command will take a
few seconds to a minute depending on your network
connection. The command downloads
the mongodb package from the npm public registry
into the node_modules directory of your project.
CRUD Operations
• CRUD (Create, Read, Update, Delete) operations allow
you to work with the data stored in MongoDB.
• The CRUD operation documentation is categorized in
two sections:
• Read Operations find and return documents stored within
your MongoDB database.
• Write Operations insert, modify, or delete documents in
your MongoDB database.
• Some operations combine aspects of read and write
operations. See our guide on compound operations to
learn more about these hybrid methods.
Create
• Use insertOne() to create a new document. insertOne() has
only one required parameter: the document to insert. If the
document does not include a field named _id, the
MongoDB Node.js driver will add one automatically.
• To create multiple documents, use insertMany()The only
argument you are required to pass to insertMany() is an
array of documents to insert.
• Both insertOne() and insertMany() allow you to pass
optional settings. One optional setting to note for
insertMany() is the boolean ordered. If an insert fails when
ordered is to true, the remaining inserts will not be
executed. If an insert fails when ordered is to false, the
remaining inserts will be executed.
Read
• To retrieve a single document from your database,
use findOne(). findOne() requires that you pass a
query object. The query can contain zero to many
properties.
• To retrieve multiple documents from your database,
use find().
• Like findOne(), find() requires you to pass a query
object that contains zero to many properties. find()
returns a cursor that you can use to iterate over the
results.
• Both findOne() and find() allow you to pass optional
settings when you call them.
Update
• Use updateOne() when you want to update a single
document.
• updateOne() has two required parameters:
• a filter object that indicates which document should be
updated and an update object that indicates the update
operations that should be applied to the document.
• To update multiple documents, you can use updateMany().
• updateMany() has the same required parameters as
updateOne(): a filter object and an update object.
• .
• Both updateOne() and updateMany() allow you to
pass optional settings to them when you call them.
upsert is one of the options you can pass
• When upsert is set to true, a new document will
be created if no document matches the query.
upsert can be really helpful as it allows you to
combine multiple operations into one: checking to
see if a document exists and then updating the
document if it exists or creating a new document
if it does not.
Delete
• To delete a single document, use deleteOne(). A filter
object that indicates the document to be deleted is the only
required parameter.
• Use deleteMqny() when you want to delete multiple
documents. Like deleteOne(), the only required parameter
is the filter object.
• Both deleteOne() and deleteMany() allow you to pass
optional settings as well.

You might also like