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

Unit 3 MongoDB

To integrate MongoDB into a Node.js environment, the document outlines steps for: 1. Installing MongoDB, including downloading, extracting, and configuring files and paths. 2. Starting and stopping MongoDB using mongod commands to initiate and terminate the database engine. 3. Administering user accounts by creating, listing, and removing users with db.createUser(), show users, and db.removeUser() commands.

Uploaded by

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

Unit 3 MongoDB

To integrate MongoDB into a Node.js environment, the document outlines steps for: 1. Installing MongoDB, including downloading, extracting, and configuring files and paths. 2. Starting and stopping MongoDB using mongod commands to initiate and terminate the database engine. 3. Administering user accounts by creating, listing, and removing users with db.createUser(), show users, and db.removeUser() commands.

Uploaded by

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

Unit 3 - MongoDB

Building the MongoDB Environment


Installing MongoDB
Starting MongoDB
Stopping MongoDB
Administering User Accounts
Creating User Accounts
Listing Users
Removing Users
Configuring Access Control
Creating a User Administrator Account
Turning on Authentication
Creating a Database Administrator Account
Administering Databases
Creating Databases
Copying Databases
Changing the Current Database
Displaying a List of Databases
Deleting Databases
Managing Collections
Creating Collections
Finding Documents in a Collection
Adding Documents to a Collection
Deleting Documents in a Collection
Updating Documents in a Collection
Displaying a List of Collections in a Database
Deleting Collections
Connecting to MongoDB from Node.js
 NoSQL - Not Only SQL databases
 Features of NoSQL
o Flexible schemas
o Horizontal scaling
o High-performance
o Enhanced functionality
o Fast queries due to the data model
o Ease of use for developers

o A collection is simply a grouping of documents that have the same or a similar purpose
o A document is a representation of a single entity of data in the MongoDB database.
o MongoDB Datatypes : comparison order from lowest to highest:

MongoDB provides several mechanisms to optimize performance, scaling, and reliability


 Indexing: Indexes improve performance for frequent queries by building a lookup index that can be easily
sorted
 Sharding: Sharding is the process of slicing up large collections of data that can be split between multiple
MongoDB servers in a cluster.
 Replications: Replication is the process of duplicating data on multiple MongoDB instances in a cluster.
Q1: Building the MongoDB Environment
Description Steps
 To integrate MongoDB into your Node.js environment, the initial step is to install
the MongoDB server.
 MongoDB offers versions for various platforms, including Linux, Windows, Solaris,
and OS X, with an enterprise version.
 Enterprise version is subscription-based, offering enhanced security, management,
and integration support.
 To install MongoDB:
Installing  Visit the MongoDB website and download the standard edition.
MongoDB (http://docs.mongodb.org/manual/installation/)
 During installation:
o Download and extract MongoDB files.
o Add <mongo_install_location>/bin to your system path.
o Create a data files directory at
<mongo_data_location>/data/db
 Start MongoDB using the console prompt with the command:
mongod –dbpath <mongo_data_location>/data/db

 After installing MongoDB, managing the database engine involves starting and
stopping it.
 To initiate the MongoDB database engine, execute the following command mongod
 For example, to start MongoDB with specific port and dbpath parameters, you can use a
command like:
mongod –port 28008 –dbpath <mongo_data_location>/data/db

Starting  Commonly used mongod command-line parameters


MongoDB  port - Specifies the TCP port for mongod to listen for client connections (Default: 27017).
 dbpath - Specifies a directory for the mongod instance to store its data.
 config - Specifies a configuration file containing runtime configurations.
 bind_ip - Specifies the IP on which mongod will bind and listen for connections
 auth - Enables database authentication for users connecting from remote hosts.
 repair - Runs a repair routine on all databases.
 quiet - Reduces reporting to the console and log file.
 help - Returns basic help and usage text.
 version - Returns the version of MongoDB.

 To halt the MongoDB database engine, ensuring a clean shutdown and termination
Stopping of current operations from the shell client:
MongoDB use admin // Switch to the admin db
db.shutdownServer() // Shut down the db engine

---------------------
Q2: Administering User Accounts
 Once MongoDB is operational, the next step is to add users for database access.
 MongoDB offers functionalities within the MongoDB shell to add, remove, and configure users.
 These actions facilitate user management, ensuring controlled and secure access to the database.
Description Steps
 Create new user accounts to control access to databases.
 Use the db.createUser() command to add a new user.
 Specify the username, password, and roles (permissions) for the new user.
 Fields used when creating users with the db.createUser() method.
Field Format Description
user String Specifies a unique username.
pwd hash or string Specifies a user password
roles Array Specifies an array of user roles
 Database roles that can be assigned to user accounts
Creating Role Description
User dbAdmin Allows the user to read from and write to the database
Accounts dbAdminAnyDatabase Allows the user to read from and write for all the database
userAdmin Allows the user to create and modify user accounts on the database
userAdminAnyDatabase Allows the user to create and modify user accounts for all the database
read Allows the user to read data from any collection within the database.
readWrite Allows the user to write to any collection within the database
readAnyDatabase Allows the user to read data from any collection for all the database
readWriteAnyDatabase Allows the user to write to any collection for all the database
Example :
use testDB // Switch to testDB
db.createUser( { user: "testUser", // Create Users with fileds & roles
pwd: "test",
roles: [ "readWrite", "dbAdmin" ] } )
 User accounts in MongoDB are stored in the db.system.users collection for each
database.
 The User object includes fields such as _id, user, pwd, roles, and other DBRoles.
 To retrieve a list of user objects, one approach is to switch to the desired database
and execute the show users command.
 For instance, switching to the admin database and listing users is accomplished with
Listing the following commands:
Users use admin // Switch to the admin db
show users // Listing users on the admin db
 The following code gets a cursor for users in the admin database and returns the
count of users:
use admin
cur = db.system.users.find()
cur.count()
 To remove users from MongoDB, the removeUser(<username>) method is used.
 Before executing this method, it's necessary to switch to the database where the user
exists.
Removing
 For instance, to remove the user "testUser" from the "testDB" database, the following
Users
commands are used in the MongoDB shell:
use testDB // Switch to testDB
db.removeUser("testUser") // Remove testUser from testDB
Q3: Configuring Access Control
 MongoDB provides authentication and authorization at a database level, where users are
defined within the context of a single database.
 User credentials for authentication purposes are stored in a collection called system.users
within each database.
 Initially, the admin database does not have any users assigned to it.
 To enhance security, the first step in setting up a new MongoDB instance is to create User
Administrator and Database Administrator accounts.
 Database Administrator account serves as a superuser, enabling the management of
databases, clustering, replication, and other MongoDB aspects.
Description Explanation
The User Administrator account allows the creation of user accounts in the
admin and other databases.
Syntax:

Creating a User
Administrator
Account Example:

Here, the username useradmin and a password of test.


 The following command attempts to authenticate the user with the
username "useradmin" and the password "test" within the currently
selected "admin" database.
 If the authentication is successful, the user gains the necessary privileges
Turning on to perform operations within that database.
Authentication
 Example:
use admin
db.auth("useradmin", "test")

 Creating a Database Administrator account in MongoDB involves using


the `createUser` method.
 This process is executed within the "admin" database and includes
adding a user with specific rights such as `readWriteAnyDatabase`,
`dbAdminAnyDatabase.
 These rights grant the user the capability to access all databases, create
Creating a
new databases, and manage MongoDB clusters and replicas.
Database
 Example:
Administrator
use admin
Account
db.createUser({ user: "dbadmin",
pwd: "test",
roles: ["readWriteAnyDatabase","dbAdminAnyDatabase"]
})
Here, username is "dbadmin," password is "test," and the assigned roles
provide extensive administrative privileges across databases.
Q4: Administering Databases
 When administering databases in the MongoDB shell, it is essential to utilize a user account
with `clusterAdmin` privileges.
 Typically, this is achieved through a Database Administrator account
 Once a Database Administrator account is created
created, it is necessary to execute various
administrative tasks mentioned below
below.
Description Explanation

Creating  Using the use command, you can create your own databases.
 Syntax: use new_dBName
Databases
 Example: use EmployeeDB // EmployeeDB is the newly created DB
 Copying a database creates an exact duplicate of the database,
database only with a
different name.
name

 MongoDB has a copyDatabase command that allows you to copy a database


Copying from one location to another.
Databases
 Syntax:: db.copyDatabase(Source, Destination , [HostName])
 Example:
use admin
db.copyDatabase("EmployeeDB", "StaffDB", "localhost:27017")
 different databases, you must change the `db`
To execute operations on differen `db
handle to point to the specific database
 ` ` command or explicitly referencing the desired
This involves using the `use`
Changing the database in MongoDB commands.
Current  /change the current database, use the following syntax:
To switch/change
Database db.getSiblingDB(dbName) or
use dbName
 Example: db = db.getSiblingDB('testDB') or
use testDb
 To display a list of databases in the system, use the show command
 Syntax : show dbs
Displaying a
List of
Databases

Output
 To delete a database from the MongoDB shell, use the dropDatabase().
 Example:
Deleting
use newDB
Databases
db.dropDatabase()
Q5: Managing Collections
 MongoDB Collections are containers for storing and organizing related documents.
 MongoDB collection is a logical grouping of JSON-like documents within a database.
 MongoDB collections support a dynamic schema.
 Collections can be indexed on specific fields to enhance query performance.
 Collections in MongoDB provide a flexible and scalable mechanism for organizing and storing data .
 A collection in MongoDB is equivalent to a table in a relational database.
 Grouping of MongoDB documents is called as collection.
Creating  Syntax : db.createCollection("collection_name")
Collections
 Example : use studentDB // Database Name : studentDB
db.createCollection("Academics") // Collection Name : Academics
 Documents in MongoDB are analogous to rows in a relational database table.
 You insert data by adding documents to a collection using insert command.
Adding Documents
to a Collection  Syntax : db. collection_name.insert({ key1: "value1", key2: "value2", ... })
 Example: db.Academics.insert({ name: "Siva", age: 21, email: "[email protected]" })
 You can update existing documents in a collection using the update() or updateOne().
Updating
Documents in a  Syntax : db.collection_name.update({ query_criteria }, { $set: { update_fields } })
Collection  Example : db.Academics.update({ name: "Siva " }, { $set: { age: 22 } })
 Documents can be removed from a collection using the remove() or deleteOne().
Deleting Documents  Syntax : db.collection_name.remove({ deletion_criteria })
in a Collection
 Example : db.Academics.remove({ name: "Siva" })
 The find() is used to query and retrieve documents from a collection.
Finding Documents  Syntax : db. collection_name.find({ query_criteria })
in a Collection
 Example: db.Academics.find({ age: { $gte: 22 } }) // gte : greater than equal to

 You can list all collections in a database using the getCollectionNames().


Displaying a List  Syntax : db.getCollectionNames()
of Collections in a
 Example : use studentDB
Database
db.getCollectionNames() // List all the collections in studentDB
 To remove a collection, you can use the drop().
 Syntax : db.collection_name.drop()
Deleting
Collections  Example : use studentDB
db.Academics.drop() // Collection Name : Academics is dropped
Q6: To connect to MongoDB from Node.js, you can use the official MongoDB Node.js driver.
Below are the steps with a simple code example:

1. Install MongoDB Node.js Driver:


- Open a terminal and navigate to your Node.js project directory.
- Run the following command to install the MongoDB Node.js driver using npm:
npm install mongodb

2. Create a MongoDB Connection:


- Require the `mongodb` module in your Node.js script.
- Use the `MongoClient` class to create a connection to your MongoDB server.

3. Access a Database:
- Use the `db` object from the connection to access a specific database.

4. Perform Database Operations:


- Use the provided `db` object to perform db operations such as insert, update, delete, and query.

5. Close the Connection:


- Always close the MongoDB connection when you are done with the database operations.

Coding :
const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017'; // Connection URL

const dbName = 'studentDByour_database_name'; // Database Name

const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });


// Create a new MongoClient
client.connect((err) => { // Connect to the MongoDB server

if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
console.log('Connected to MongoDB');

const db = client.db(dbName); // Access a specific database


// Perform database operations (e.g., insert, update, delete, query)
// ...

client.close(); // Close the MongoDB connection


});

–––––––––

You might also like