Unit 3 MongoDB
Unit 3 MongoDB
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:
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
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:
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
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
3. Access a Database:
- Use the `db` object from the connection to access a specific database.
Coding :
const { MongoClient } = require('mongodb');
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
console.log('Connected to MongoDB');
–––––––––