Unit 3
Unit 3
However, NoSQL databases may not be suitable for all applications, as they may not
provide the same level of data consistency and transactional guarantees as traditional
relational databases. It is important to carefully evaluate the specific needs of an
application when choosing a database management system.
NoSQL originally referring to non SQL or non relational is a database that provides a
mechanism for storage and retrieval of data. This data is modeled in means other than
the tabular relations used in relational databases. Such databases came into existence in
the late 1960s, but did not obtain the NoSQL moniker until a surge of popularity in the
early twenty-first century. NoSQL databases are used in real-time web applications
and big data and their use are increasing over time.
NoSQL systems are also sometimes called Not only SQL to emphasize the fact that
they may support SQL-like query languages. A NoSQL database includes simplicity of
design, simpler horizontal scaling to clusters of machines and finer control over
availability. The data structures used by NoSQL databases are different from those
used by default in relational databases which makes some operations faster in NoSQL.
The suitability of a given NoSQL database depends on the problem it should solve.
NoSQL databases, also known as “not only SQL” databases, are a new type of
database management system that have gained popularity in recent years. Unlike
traditional relational databases, NoSQL databases are designed to handle large
amounts of unstructured or semi-structured data, and they can accommodate dynamic
changes to the data model. This makes NoSQL databases a good fit for modern web
applications, real-time analytics, and big data processing.
Data structures used by NoSQL databases are sometimes also viewed as more flexible
than relational database tables. Many NoSQL stores compromise consistency in favor
of availability, speed and partition tolerance. Barriers to the greater adoption of
NoSQL stores include the use of low-level query languages, lack of standardized
interfaces, and huge previous investments in existing relational databases.
Dynamic schema: NoSQL databases do not have a fixed schema and can
accommodate changing data structures without the need for migrations or
schema alterations.
Horizontal scalability: NoSQL databases are designed to scale out by adding
more nodes to a database cluster, making them well-suited for handling large
amounts of data and high levels of traffic.
Document-based: Some NoSQL databases, such as MongoDB, use a document-
based data model, where data is stored in semi-structured format, such as JSON
or BSON.
Key-value-based: Other NoSQL databases, such as Redis, use a key-value data
model, where data is stored as a collection of key-value pairs.
Column-based: Some NoSQL databases, such as Cassandra, use a column-
based data model, where data is organized into columns instead of rows.
Distributed and high availability: NoSQL databases are often designed to be
highly available and to automatically handle node failures and data replication
3
{
title: 'Geeksforgeeks',
by: 'Harshit Gupta',
url: 'https://www.geeksforgeeks.org',
type: 'NoSQL'
}
SQL databases store data in tabular format. This data is stored in a predefined data
model which is not very much flexible for today’s real-world highly growing
applications. Modern applications are more networked, social and interactive than
ever. Applications are storing more and more data and are accessing it at higher rates.
NoSQL databases are more scalable and provide superior performance. MongoDB is
Page
such a NoSQL database that scales by adding more and more servers and increases
productivity with its flexible document model.
RDBMS vs MongoDB:
RDBMS has a typical schema design that shows number of tables and the relationship
between these tables whereas MongoDB is document-oriented. There is no concept of
schema or relationship.
Complex transactions are not supported in MongoDB because complex join operations
are not available.
MongoDB allows a highly flexible and scalable document structure. For example, one
data document of a collection in MongoDB can have two fields whereas the other
document in the same collection can have four.
MongoDB is faster as compared to RDBMS due to efficient indexing and storage
techniques.
There are a few terms that are related in both databases. What’s called Table in
RDBMS is called a Collection in MongoDB. Similarly, a Row is called a Document
and a Column is called a Field. MongoDB provides a default ‘_id’ (if not provided
explicitly) which is a 12-byte hexadecimal number that assures the uniqueness of
every document. It is similar to the Primary key in RDBMS.
Features of MongoDB:
Document Oriented: MongoDB stores the main subject in the minimal number of
documents and not by breaking it up into multiple relational structures like RDBMS.
For example, it stores all the information of a computer in a single document called
Computer and not in distinct relational structures like CPU, RAM, Hard disk, etc.
Indexing: Without indexing, a database would have to scan every document of a
collection to select those that match the query which would be inefficient. So, for
efficient searching Indexing is a must and MongoDB uses it to process huge volumes
of data in very less time.
Scalability: MongoDB scales horizontally using sharding (partitioning data across
various servers). Data is partitioned into data chunks using the shard key, and these
data chunks are evenly distributed across shards that reside across many physical
servers. Also, new machines can be added to a running database.
Replication and High Availability: MongoDB increases the data availability with
multiple copies of data on different servers. By providing redundancy, it protects the
database from hardware failures. If one server goes down, the data can be retrieved
7
easily from other active servers which also had the data stored on them.
Page
Aggregation: Aggregation operations process data records and return the computed
results. It is similar to the GROUPBY clause in SQL. A few aggregation expressions
are sum, avg, min, max, etc
Where do we use MongoDB?
Big Data: If you have huge amount of data to be stored in tables, think of MongoDB
before RDBMS databases. MongoDB has built-in solution for partitioning and
sharding your database.
Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is
schema-less. Adding a new field does not effect old documents and will be very easy.
Distributed data Since multiple copies of data are stored across different servers,
recovery of data is instant and safe even if there is a hardware failure.
Language Support by MongoDB:
MongoDB currently provides official driver support for all popular programming
languages like C, C++, Rust, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go,
and Erlang.
Basic Querying with MongoDB Shell
MongoDB Shell is the quickest way to connect, configure, query, and work with your
MongoDB database.
It acts as a command-line client of the MongoDB server.
The MongoDB Shell is a standalone, open-source product and developed separately
from the MongoDB Server under the Apache 2 license.
It is a fully functional JavaScript and Node.js 14.x REPL for interacting with
MongoDB servers.
MongoDB Shell is already installed with MongoDB. You can find it in the installation
directory where you installed MongoDB. By default, it is "C:\Program
Files\MongoDB\Server". Open the installation folder and appropriate version folder
and go to the "bin" folder. Here, "mongo.exe" is MongoDB shell.
already have a new MongoDB shell. If you don't find it, then you need to install it
Page
separately.
The new MongoDB Shell mongosh has some more features than old shell mongo such
as intelligent autocomplete and syntax highlighting, easy to understand error messages,
formatting feature to present the output in a readable format, etc. However, all the
commands will be executed in mongosh as well as mongo shell.
Install mongosh
1. To install the new MongoDB shell (mongosh), visit www.mongodb.com and click
on Product menu -> Tools -> Database Shell
2. On the MongoDB Shell page, click on the Download button to download the
shell.
3. This will take you to a page where you can select a version, platform, and
package to download
4. Click on the Download button to download the installer file
5. Now, click on the downloaded installer file to start the installation wizard
6. Click Next to go to next step shown below.
7. Once installation completes, click the Finish button to close the wizard.
8. This should have installed mongosh in "C:\Program Files\mongosh" folder on
Windows
9. Click on the mongosh.exe to open a new MongoDB shell
MongoDB Shell Commands
MongoDB Shell is the quickest way to connect, configure, query,
and work with your MongoDB database. It acts as a command-line client of the
MongoDB server.
You can start MongoDB Shell by executing mongo or mongosh command on the
command prompt/terminal. mongosh is the new MongoDB shell with some more
features than the old mongo shell.
mongosh <commands>
The --help command display all the commands which you can use
with mongo or mongosh
MongoDB provides you read operations to retrieve documents from the collection or
query a collection for a document. You can perform read operations using the
db.collection.find() method. This method selects or views the documents from the
9
In this example, we are selecting only those documents that satisfy the given condition,
Page
i.e, language: “C#”. Or in other words, we are selecting only those contributors who
are working with C# language.
Syntax:
db.collection.find({field: value})
Select documents that satisfy the given condition (Using Query operators):
In this example, we are selecting only those documents that satisfy the given condition,
here the condition is created using query operators. Or in words, we are selecting only
those contributors who are working with C# or Java language.
Syntax:
db.collection.find({field: {operator: value}})
Here, we are using $in operator. This operator is used to matches any of the values
specified in the given array.
db.contributor.find({language: {$in:[ "Java", "C#"]}}).pretty()
Step 2: Now, you have to install express for that, you will write a command npm i
express.
Step 3: After that, go ahead and install body-parser. For that write command on your
11
terminal.
Page
Now, the body-parser is installed in your system.
Step 4: Go ahead and write a basic Express app that is common in every express
application.
<!DOCTYPE html>
<html>
<head>
<title>Body-Parser Module Demo</title>
</head>
<body>
<h1>Demo Form</h1>
index.js
// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
15
Page
NodeJS MongoDB Connection
MongoDB will create the database if it does not exist, and make a connection to it.
Save the code above in a file called "demo_create_mongo_db.js" and run the
file:
16
Run "demo_create_mongo_db.js"
Page
C:\Users\Your Name>node demo_create_mongo_db.js
Database created!
res.redirect("/thank-you");
Page
}
});
});
Contact.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/contact" method="post">
<input type="text" placeholder="Email" name="email">
<input type="text" placeholder="Query" name="query">
<button type="submit">Submit</button>
</form>
</body>
</html>
mongoose.connect("mongodb://localhost:27017/newCollection", {
18
useNewUrlParser: true,
Page
useUnifiedTopology: true
});
const contactSchema = {
email: String,
query: String,
};
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/public'));
if (err) {
Page
throw err;
} else {
res.render("contact");
}
});
});
app.listen(3000, function(){
console.log("App is running on Port 3000");
});
Output:
20
Page
Page
21
Adding and Retrieving Data to MongoDB from NodeJS
It also takes a callback function where you can work with any errors, or the
result of the insertion
Save the code above in a file called "demo_mongodb_insert.js" and run the file:
Run "demo_mongodb_insert.js"
1 document inserted
22
Page
Insert Multiple Documents
It also takes a callback function where you can work with any errors, or the
result of the insertion:
Run "demo_mongodb_insert_multiple.js"
23
Find One
To select data from a collection in MongoDB, we can use the findOne() method.
The first parameter of the findOne() method is a query object. In this example
we use an empty query object, which selects all documents in a collection (but
returns only the first document).
Save the code above in a file called "demo_mongodb_findone.js" and run the
file:
Run "demo_mongodb_findone.js"
Company Inc.
24
Page
Find All
To select data from a table in MongoDB, we can also use the find() method.
The first parameter of the find() method is a query object. In this example we
use an empty query object, which selects all documents in the collection.
Save the code above in a file called "demo_mongodb_find.js" and run the file:
Run "demo_mongodb_find.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet
4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain
21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley
345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a , name: 'Betty', address: 'Green Grass
1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st
331'},
25
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', address: 'Central st
954'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: 'Main Road
989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway
1633'}
]
MySQL Database
To be able to experiment with the code examples, you should have MySQL
installed on your computer.
Once you have MySQL up and running on your computer, you can access it by
using Node.js.
To access a MySQL database with Node.js, you need a MySQL driver. This
tutorial will use the "mysql" module, downloaded from NPM.
To download and install the "mysql" module, open the Command Terminal and
execute the following:
Create Connection
demo_db_connection.js
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Save the code above in a file called "demo_db_connection.js" and run the file:
Run "demo_db_connection.js"
Connected!
Now you can start querying the database using SQL statements.
Query a Database
Use SQL statements to read from (or write to) a MySQL database. This is also
called "to query" the database.
The connection object created in the example above, has a method for querying
the database:
27
con.connect(function(err) {
Page
The query method takes an sql statements as a parameter and returns the
result.
28
Page