Aim: To install MongoDB on Windows, Linux, and macOS.
Procedure:
1. Windows Installation
mongod --version
2. Linux Installation (Ubuntu/Debian)
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl start mongod
mongod --version
3. macOS Installation
brew tap mongodb/brew
brew install mongodb-community@5.0
brew services start mongodb-community@5.0
mongod --version
MCQs:
Conclusion: In this practical, we successfully installed MongoDB on different operating systems, including Windows, Linux, and macOS. We also verified the installation and ensured MongoDB services were running correctly.
Aim: To perform Create, Read, Update, and Delete (CRUD) operations in MongoDB.
Procedure:
use myDatabase
This command creates and switches to the database myDatabase
.
db.users.insertOne({"name": "Alice", "age": 25, "city": "New York"})
db.users.find()
db.users.updateOne({"name": "Alice"}, {$set: {"age": 26}})
db.users.deleteOne({"name": "Alice"})
MCQs:
use myDatabase
db.collectionName.insertOne({})
db.collectionName.find()
Conclusion: In this practical, we successfully performed basic CRUD operations in MongoDB, including creating databases, inserting, retrieving, updating, and deleting documents.
Aim: To implement schema design using embedded documents and references in MongoDB.
Procedure:
db.users.insertOne({
"name": "Alice",
"address": { "street": "123 Main St", "city": "New York" }
})
db.users.insertOne({
"_id": ObjectId("60c72b2f9af1f5c4b1c2d123"),
"name": "Alice"
})
db.orders.insertOne({
"user_id": ObjectId("60c72b2f9af1f5c4b1c2d123"),
"product": "Laptop",
"price": 1000
})
$lookup
**(Reference Query):db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user_details"
}}
])
MCQs:
Conclusion: In this practical, we implemented schema design using embedded documents and references for efficient data modelling in MongoDB. We explored when to use each approach based on data access patterns and scalability needs.
Aim: To create indexes in MongoDB to enhance query performance.
Types of Indexes in MongoDB:
Procedure:
db.users.createIndex({ "name": 1 })
This command creates an ascending index on the name
field.
db.users.createIndex({ "name": 1, "age": -1 })
This command creates an index on both name
(ascending) and age
(descending), improving queries that filter using both fields.
db.users.getIndexes()
This command retrieves all indexes created on the users
collection.
db.users.find({ "name": "Alice" }).explain("executionStats")
This command helps analyze how MongoDB executes queries and whether an index is being used.
db.users.dropIndex("name_1")
This command removes the index on the name
field if no longer needed.
MCQs:
CREATE INDEX index_name ON table_name (column_name);
db.collectionName.createIndex({ age: 1 })
Conclusion: In this practical, we successfully created and managed indexes in MongoDB to optimize query performance. We also analysed query execution plans to understand the impact of indexes on database efficiency.
Aim: To perform aggregation operations such as grouping, filtering, projection, and sorting in MongoDB.
Description: Aggregation in MongoDB allows users to process and analyze data efficiently. The aggregation pipeline consists of multiple stages where data undergoes transformation before producing the desired result. Common stages include:
$match
- Filters documents based on a condition.$group
- Groups documents by a specified field and applies aggregate functions.$project
- Modifies the structure of documents by including/excluding fields.$sort
- Sorts documents in ascending or descending order.Procedure:
$match
:db.sales.aggregate([
{ $match: { "category": "Electronics" } }
])
$group
:db.sales.aggregate([
{ $group: { _id: "$category", totalSales: { $sum: "$price" } } }
])
$project
:db.sales.aggregate([
{ $project: { _id: 0, product: 1, price: 1 } }
])
$sort
:db.sales.aggregate([
{ $sort: { price: -1 } }
])
MCQs:
GROUP BY
$match
HAVING
$sort
Conclusion: In this practical, we successfully performed aggregation operations in MongoDB using stages like $match
, $group
, $project
, and $sort
to analyse and process data efficiently.
Aim: To aggregate data from multiple collections using the $lookup
stage in MongoDB.
Description: Aggregation in MongoDB allows us to process data records and return computed results. The $lookup
stage is used to perform joins across multiple collections, enabling us to retrieve related data efficiently.
Procedure:
db.users.insertMany([
{ "_id": ObjectId("60c72b2f9af1f5c4b1c2d123"), "name": "Alice", "email": "alice@example.com" },
{ "_id": ObjectId("60c72b2f9af1f5c4b1c2d124"), "name": "Bob", "email": "bob@example.com" }
])
db.orders.insertMany([
{ "user_id": ObjectId("60c72b2f9af1f5c4b1c2d123"), "product": "Laptop", "price": 1000 },
{ "user_id": ObjectId("60c72b2f9af1f5c4b1c2d124"), "product": "Phone", "price": 500 }
])
$lookup
:db.orders.aggregate([
{
$lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user_info"
}
}
])
This query joins the orders
collection with the users
collection using the user_id
field and returns the user information along with order details.
MCQs:
$lookup
from
$match
null
or an empty array`Conclusion: In this practical, we successfully performed data aggregation from multiple collections using the $lookup
stage in MongoDB. This method allows us to efficiently join related data across collections, similar to SQL joins.
Aim: To configure a sharded cluster in MongoDB for efficient data distribution and scalability.
Description: Sharding is a method used in MongoDB to distribute data across multiple servers, ensuring better performance and high availability. This technique helps manage large datasets by splitting data into smaller chunks and distributing them across different shards.
Procedure:
sh.enableSharding("ecommerce")
This enables sharding on the ecommerce database.
sh.addShard("shard1.example.com:27017")
This command adds a new shard to the MongoDB cluster.
sh.shardCollection("ecommerce.orders", { "order_id": "hashed" })
This command enables sharding on the orders
collection using order_id
as the shard key.
sh.status()
This command displays the current sharding configuration and status of the cluster.
MCQs:
mongos
)sh.enableSharding("database_name")
Conclusion: In this practical, we successfully configured a sharded cluster in MongoDB to distribute data efficiently. Sharding enhances performance by balancing data across multiple servers, reducing load, and ensuring better scalability.
Aim: To perform database backups in MongoDB using the mongodump
command.
Description: Backing up a database is essential to prevent data loss and ensure recovery in case of failure. MongoDB provides the mongodump
utility, which creates a binary export of the database that can be restored later.
Procedure:
mongodump --out /backup
This command creates a backup of all databases and stores them in the /backup
directory.
mongodump --db myDatabase --out /backup
This command backs up only the myDatabase
database.
mongodump --db myDatabase --collection users --out /backup
This command backs up the users
collection from myDatabase
.
After running mongodump
, check the /backup
directory for BSON and metadata files. These files can be used for restoration.
MCQs:
dump/
--db
mongodump --collection users --db myDatabase
--out
Conclusion: In this practical, we successfully performed database backups using the mongodump
command in MongoDB. This ensures data safety by allowing us to restore databases and collections when needed.
Aim: To restore databases and collections in MongoDB using the mongorestore
command.
Description: The mongorestore
utility is used to restore database backups created by mongodump
. It allows users to recover entire databases or specific collections from a backup directory. This is essential for disaster recovery and data migration.
Procedure:
mongorestore --db myDatabase /backup/myDatabase
This command restores the myDatabase
database from the backup directory.
mongorestore --db myDatabase --collection users /backup/myDatabase/users.bson
This command restores only the users
collection in myDatabase
.
mongorestore /backup
This command restores all databases stored in the /backup
directory.
mongorestore --drop --db myDatabase /backup/myDatabase
The --drop
option ensures existing data is removed before restoring the backup.
MCQs:
mongodump
backup--db
mongorestore --collection users --db myDatabase dump/
dump/
directory in the working directoryConclusion: In this practical, we successfully restored databases and collections using the mongorestore
command in MongoDB. This ensures that data can be recovered efficiently in case of accidental deletion or system failures.
Aim: To enable authentication and create user roles in MongoDB for secure access control.
Description: MongoDB provides role-based access control (RBAC) to manage user permissions securely. Authentication ensures that only authorized users can access and modify data. Users can be assigned different roles based on their privileges.
Procedure:
Edit the MongoDB configuration file (mongod.conf
) and add the following lines:
security:
authorization: enabled
Restart the MongoDB service to apply changes.
mongo
use admin
db.createUser({
user: "admin",
pwd: "securepassword",
roles: [ { role: "root", db: "admin" } ]
})
This command creates an admin user with full database access.
sudo systemctl restart mongod
mongo -u admin -p securepassword --authenticationDatabase admin
db.createUser({
user: "readonlyUser",
pwd: "readonlypass",
roles: [ { role: "read", db: "myDatabase" } ]
})
This user has read-only access to myDatabase
.
MCQs:
--auth
optionroot
db.createUser({ user: "username", pwd: "password", roles: ["role_name"] })
read
db.createUser()
Conclusion: In this practical, we successfully enabled authentication in MongoDB and created user roles to control access. Role-based access control (RBAC) ensures database security by assigning appropriate permissions to users.
Made By SOU Student for SOU Students