1. What is Database Administration?
Database Administration (DBA) is the process of managing, maintaining, securing, and monitoring a database system to ensure that data is stored safely, accessed efficiently, and remains available when required.
A person who performs these activities is called a Database Administrator (DBA).
In MongoDB, database administration involves managing databases, collections, documents, users, permissions, backups, replication, sharding, performance, and server configuration.
2. Main Responsibilities of a MongoDB Database Administrator
1. Database Management
Create, list, switch, and delete databases and manage collections and documents.
Example: use college
2. Security Management
Create users, assign roles, and control access to databases using authentication and authorization.
3. Backup and Recovery
Back up databases using mongodump and restore them using mongorestore to recover data after failures.
4. Performance Optimization
Create indexes, analyze queries, and monitor resource usage to improve database performance.
5. Replication and High Availability
Configure replica sets to maintain copies of data and support automatic failover when an eligible primary becomes unavailable.
6. Sharding and Scalability
Distribute data across multiple servers when a single server cannot efficiently handle the workload.
3. Important MongoDB Administration Commands
The following examples use the MongoDB Shell (mongosh).
| Task | Command | Purpose |
|---|---|---|
| Show databases | show dbs | Display available databases |
| Create or switch database | use college | Select the college database |
| Show collections | show collections | Display collections |
| Insert a document | db.students.insertOne({name:"Amit", age:20}) | Add a student record |
| Display documents | db.students.find() | Retrieve student records |
| Check database statistics | db.stats() | Display database statistics |
| Check collection statistics | db.students.stats() | Display collection statistics |
| List users | db.getUsers() | Display users in the current database |
| Check server status | db.serverStatus() | Display server-level statistics |
Note: MongoDB creates a database physically when data is written to it or when an applicable database-creation operation occurs. Merely executing use college selects the database; it does not necessarily create it on disk.
4. Practical Examples of Database Administration
A. Creating a database and collection
use college
db.students.insertOne({
rollno: 1,
name: "Rahul",
course: "BCA",
semester: 3
})
show collections
db.students.find()
Explanation:
use collegeselects the database.insertOne()inserts a student document.- MongoDB creates the
studentscollection if necessary. find()displays the stored documents.
B. Creating an index for better performance
db.students.createIndex({ rollno: 1 })
db.students.find({ rollno: 1 })
An index can improve the speed of searches on rollno. However, indexes consume storage and can slow down writes slightly, so they should be selected according to query patterns.
C. Creating a database user
Run this example as an administrator with permission to create users:
use college
db.createUser({
user: "collegeUser",
pwd: passwordPrompt(),
roles: [
{ role: "readWrite", db: "college" }
]
})
This creates a user with read and write permissions on the college database. passwordPrompt() asks for the password interactively in supported versions of mongosh.
For production systems, enable authentication, use strong credentials, and grant only the permissions required by each user.
D. Taking a backup
Run this command in Windows Command Prompt or PowerShell, not inside mongosh:
mongodump --db=college --out="D:\MongoBackup"
This exports the college database to the specified backup directory.
To restore it:
mongorestore --db=college "D:\MongoBackup\college"
For modern MongoDB Database Tools, verify the supported options for your version. Test backups by restoring them in a separate environment.
E. Monitoring database performance
db.serverStatus()
This command provides information about connections, memory, operations, storage engine activity, and other server metrics. Access to some information depends on user privileges.
5. MongoDB Administration Tools
MongoDB Compass
A graphical interface for browsing documents, managing collections, building indexes, and running queries.
MongoDB Shell (mongosh)
A command-line tool used to execute database operations, manage users, and inspect server information.
MongoDB Atlas
A managed cloud database service that provides monitoring, backups, security controls, and scaling features according to the selected plan.
6. Advantages of Database Administration in MongoDB
- Data security: Protects information from unauthorized access.
- Data recovery: Helps recover data from backups and failures.
- High availability: Replication helps keep applications operational during certain server failures.
- Better performance: Indexing and query analysis improve response times.
- Scalability: Sharding supports growing data volumes and workloads.
- Reliability: Monitoring helps administrators detect problems early.
- Data integrity: Validation rules and appropriate application logic help maintain accurate data.
Create User and Assign Privileges in MongoDB
In MongoDB, we can create a user and assign privileges using the db.createUser() method. Privileges determine which operations a user can perform, such as reading, inserting, updating, or deleting data.
1. Syntax to Create a User
db.createUser({
user: "username",
pwd: "password",
roles: [
{ role: "readWrite", db: "database_name" }
]
})
user: Name of the new user.pwd: Password of the user.roles: Permissions assigned to the user.db: Database on which the permissions apply.
2. Example: Create a User and Assign Privileges
Suppose we want to create a user named student for the stud database with permission to read and write data.
Step 1: Open MongoDB Shell
Open Command Prompt and run:
mongosh
Step 2: Select the database
use stud
Step 3: Create the user
db.createUser({
user: "student",
pwd: "Student@123",
roles: [
{ role: "readWrite", db: "stud" }
]
})
Expected output:
{ ok: 1 }
The user student has now been created with read and write privileges on the stud database.
3. MongoDB Built-in Roles
| Role | Privileges |
|---|---|
read | Read data from the database |
readWrite | Read, insert, update, and delete data |
dbAdmin | Perform database administration tasks |
dbOwner | Perform administrative actions and read/write operations on a database |
userAdmin | Manage users and roles for a database |
root | Full administrative privileges across the deployment |
Note: Avoid assigning root unless full administrative access is genuinely required.
4. Assign Multiple Privileges to a User
We can assign more than one role to a user.
use stud
db.createUser({
user: "adminuser",
pwd: "Admin@123",
roles: [
{ role: "readWrite", db: "stud" },
{ role: "dbAdmin", db: "stud" }
]
})
Here, adminuser can read and modify data and perform database administration tasks on stud.
5. Grant Additional Privileges to an Existing User
If the user already exists, use db.grantRolesToUser().
use stud
db.grantRolesToUser(
"student",
[
{ role: "dbAdmin", db: "stud" }
]
)
This adds the dbAdmin role without removing the user’s existing roles.
6. View Users and Their Privileges
To display users in the current database:
db.getUsers()
To view a specific user’s details:
db.getUser("student")
7. Remove Privileges from a User
Use db.revokeRolesFromUser().
db.revokeRolesFromUser(
"student",
[
{ role: "dbAdmin", db: "stud" }
]
)
This removes the dbAdmin role from student but preserves other roles.
8. Delete a User
db.dropUser("student")
This permanently removes the user from the current database.
9. Test User Login
If MongoDB authentication is enabled, connect using:
mongosh -u student -p --authenticationDatabase stud
Enter the password when prompted. The user should be able to access the permissions assigned to them.
Important: Creating a MongoDB user does not automatically enable authentication on the server. Authentication must be configured in mongod.cfg if it is not already enabled.
Practical Summary
- Create a user:
db.createUser() - Grant privileges:
db.grantRolesToUser() - View privileges:
db.getUser() - Revoke privileges:
db.revokeRolesFromUser() - Delete a user:
db.dropUser()