Full Stack UNIT 3
Full Stack UNIT 3
Full Stack UNIT 3
MongoDB
SYLLABUS:
Understanding NoSQL and MongoDB – Building
MongoDB Environment – User accounts – Access
control – Administering databases – Managing
collections – Connecting to MongoDB from Node.js –
simple applications
Understanding NoSQL and MongoDB:
Is MongoDB NoSQL?
unstructured data.
What is MongoDB?
files using their binary storage objects. Data storage is very compact and
efficient, perfect for high data volumes. MongoDB stores data in JSON-
The model of each document will be different in size and content from
each other. The data model features allow storing arrays and complex
What is NoSQL?
Characteristics of NoSQL
Below are the characteristics of NoSQL:
Multi-Model: This feature of NoSQL databases makes them highly
flexible when handling data.
Easily Scalable: This feature of NoSQL databases easily scales to adapt
to the massive volumes and complexity of cloud applications. This
scalability improves performance, allowing continuous availability and
high read/write speeds.
Flexible: This feature of NoSQL databases allows you to process all
varieties of data. It can process structured, semi-structured, and
unstructured data. It works on many processors—NoSQL systems will
enable you to store your database on multiple processors and maintain
high-speed performance.
Less Downtime: The elastic nature of NoSQL allows for the workload to
be spread across any number of servers automatically.
the large volume of social media and web data. NoSQL database was a
rescue for Big Data. NoSQL database allowed the programme1r to
execute the database with ease and efficiency. NoSQL database is of four
types. NoSQL can handle far more data in terms of volume and
Disadvantages of MongoDB :
Once the download is complete, double click this setup file to install it. Follow the
steps:
1. Click Next.
2. Now, choose Complete to install MongoDB completely.
3. Then, select the radio button "Run services as Network service
user."
In this way, you can start your MongoDB database. Now, for running
MongoDB primary client system, you have to use the command:
C:\Program Files\MongoDB\Server\4.0\bin>mongo.exe
Datatypes in MongoDB:
Create a User:
Prerequisites
To be able to create users, you need to:
For routine user creation, you must possess the following permissions:
Procedure:
Connect and authenticate
Using mongosh , connect to your primary mongod or, in a sharded cluster, connect to
your mongos and authenticate as a user administrator or a user with the required
privileges:
After authenticating as the user administrator, use the db.createUser() method to create
additional users. You can assign any built-in roles or user-defined roles to the users.
The following operation adds a user myTester to the test database who has
the readWrite role in the test database as well as the read role in the reporting database.
use test
db.createUser(
user: "myTester",
The database where you create the user (in this example, test) is that
user's authentication database. Although the user authenticates to this
database, the user can have roles in other databases. The user's
authentication database does not limit the user's privileges.
As the user myTester, you have privileges to perform read and write
operations in the test database (as well as perform read operations in
the reporting database). Once authenticated as myTester, insert a
document into a collection in the test database. For example, you can
perform the following insert operation in the test database:
db.foo.insertOne( { x: 1, y: 1 } )
MongoDB does not enable access control by default. You can enable
authorization using the --auth or the security.authorization setting.
Enabling internal authentication also enables client authorization.
Roles
Access
Roles never limit privileges. If a user has two roles, the role with the
greater access takes precedence.
For example, if you grant the read role on a database to a user that
already has the readWriteAnyDatabase role, the read grant
does not revoke write access on the database.
Authentication Restrictions
Inherited Privileges
A role can include one or more existing roles in its definition, in which
case the role inherits all the privileges of the included roles.
A role can inherit privileges from other roles in its database. A role
created on the admin database can inherit privileges from roles in any
database.
You can view the privileges for a role by issuing the rolesInfo command
with the showPrivileges and showBuiltinRoles fields both set to true.
You can assign roles to users during the user creation. You can also
update existing users to grant or revoke roles. For a full list of user
management methods, see User Management
A user assigned a role receives all the privileges of that role. A user can
have multiple roles. By assigning to the user roles in various databases,
a user created in one database can have permissions to act on other
databases.
NOTE:
LDAP Authorization
Administraion :
What is Administration in MongoDB?
Managing Collections :
MongoDB stores documents in collections. Collections are analogous to
Create a Collection :
If a collection does not exist, MongoDB creates the collection when you first
store data for that collection.
db.myNewCollection2.insertOne( { x: 1 } )
db.myNewCollection3.createIndex( { y: 1 } )
Explicit Creation :
Document Validation :
By default, a collection does not require its documents to have the same
schema; i.e. the documents in a single collection do not need to have the
same set of fields and the data type for a field can differ across documents
within a collection.
Unique Identifiers :
To retrieve the UUID for a collection, run either the listCollections command or
the db.getCollectionInfos() method.
Connect to a MongoDB Database Using
Node.js :
Install Node.js :
First, make sure you have a supported version of Node.js installed. The current
version of MongoDB Node.js Driver requires Node 4.x or greater. See
the MongoDB Compatability docs for more information on which version of
Node.js is required for each version of the Node.js driver.
If you don't have the MongoDB Node.js Driver installed, you can install it
with the following command.
npm install mongodb
At the time of writing, this installed version 3.6.4 of the driver. Running npm
list mongodb will display the currently installed driver version number.
Head over to Atlas and create a new cluster in the free tier. At a high level,
a cluster is a set of nodes where copies of your database will be stored.
Once your tier is created, load the sample data. If you're not familiar with
how to create a new cluster and load the sample data, check out this video
tutorial from MongoDB Developer Advocate Maxime Beugnet.
Get started with an M0 cluster on Atlas today. It's free forever, and it's the
easiest way to try out the steps in this blog series.
The Wizard will prompt you to add your current IP address to the IP Access
List and create a MongoDB user if you haven't already done so. Be sure to
note the username and password you use for the new MongoDB user as
you'll need them in a later step.
Import MongoClient
The MongoDB module exports MongoClient, and that’s what we’ll use to
connect to a MongoDB database. We can use an instance of MongoClient
to connect to a cluster, access the database in that cluster, and close the
connection to that cluster.
const {MongoClient} = require('mongodb');
Create our main function
Let’s create an asynchronous function named main() where we will connect
to our MongoDB cluster, call functions that query our database, and
disconnect from our cluster.
async function main() {
// we'll add code here soon
}
The first thing we need to do inside of main() is create a constant for our
connection URI. The connection URI is the connection string you copied in
Atlas in the previous section. When you paste the connection string, don't
forget to update <username> and <password> to be the credentials for the
user you created in the previous section. The connection string includes
a <dbname> placeholder. For these examples, we'll be using
the sample_airbnb database, so replace <dbname> with sample_airbnb.
Note: the username and password you provide in the connection string are
NOT the same as your Atlas credentials.
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url> to
reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?ret
ryWrites=true&w=majority";
Note: When you run this code, you may see DeprecationWarnings around
the URL string parserand the Server Discover and Monitoring engine. If you
see these warnings, you can remove them by passing options to the
MongoClient. For example, you could instantiate MongoClient by calling new
MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }).
See the Node.js MongoDB Driver API documentation for more information
on these options.
Now we're ready to use MongoClient to connect to our
cluster. client.connect() will return a promise. We will use
the await keyword when we call client.connect() to indicate that we should
block further execution until that operation has completed.
await client.connect();
Now we are ready to interact with our database. Let's build a function that
prints the names of the databases in this cluster. It's often useful to contain
this logic in well named functions in order to improve the readability of your
codebase. Throughout this series, we'll create new functions similar to the
function we're creating here as we learn how to write different types of
queries. For now, let's call a function named listDatabases().
await listDatabases(client);
Let’s wrap our calls to functions that interact with the database in
a try/catch statement so that we handle any unexpected errors.
try {
await client.connect();
await listDatabases(client);
} catch (e) {
console.error(e);
}
Once we have our main() function written, we need to call it. Let’s send the
errors to the console.
main().catch(console.error);
Putting it all together, our main() function and our call to it will look
something like the following.
async function main(){
/**
* Connection URI. Update <username>, <password>, and <your-cluster-url>
to reflect your cluster.
* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
*/
const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/test
?retryWrites=true&w=majority";
try {
// Connect to the MongoDB cluster
await client.connect();
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
This function will retrieve a list of databases in our cluster and print the
results in the console.
async function listDatabases(client){
databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};
Applications of MongoDB :
1. Web Applications :
MongoDB is widely used across various web applications as the primary data
store. One of the most popular web development stacks, the MEAN
stack employs MongoDB as the data store (MEAN stands for MongoDB,
ExpressJS, AngularJS, and NodeJS).
2. Big Data :
MongoDB also provides the ability to handle big data. Big Data refers to
massive data that is fast-changing, can be quickly accessed and highly available
for addressing needs efficiently. So, it can be used in applications where Big
Data is needed.
4. Synchronization :
MongoDB can easily handle complicated things that need synchronization with
each other entirely. So, it is mainly used in gaming applications. An example
gaming application developed using MongoDB as a database is “EA”. EA is a
world-famous gaming studio that is using MongoDB Database for its game
called FIFA Online 3.
5. Ecommerce :
For e-commerce websites and product data management and solutions, we can
use MongoDB to store information because it has a flexible schema well suited
for the job. They can also determine the pattern to handle interactions between
user’s shopping carts and inventory using “Inventory Management.”
MongoDB also has a report called “Category Hierarchy,” which will describe
the techniques to do interaction with category hierarchies in MongoDB .
Advantages of MongoDB :
Flexible Database
Sharding
High Speed
High Availability
Scalability