0% found this document useful (0 votes)
7 views12 pages

ADBMS - PR 1 MongoDB - Practical - StudentDB

The document provides a comprehensive guide on using MongoDB for managing a student database, covering the creation of databases and collections, as well as operations like inserting, updating, and deleting documents. It includes practical examples for various MongoDB commands and query execution, demonstrating functionalities such as batch inserts, document updates using modifiers, and complex queries. Additionally, it outlines the use of different query criteria and cursor options for retrieving data effectively.

Uploaded by

Sanjay Thorat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views12 pages

ADBMS - PR 1 MongoDB - Practical - StudentDB

The document provides a comprehensive guide on using MongoDB for managing a student database, covering the creation of databases and collections, as well as operations like inserting, updating, and deleting documents. It includes practical examples for various MongoDB commands and query execution, demonstrating functionalities such as batch inserts, document updates using modifiers, and complex queries. Additionally, it outlines the use of different query criteria and cursor options for retrieving data effectively.

Uploaded by

Sanjay Thorat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Advanced DBMS :

1. Create a database with suitable example using MongoDB and implement


• Inserting and saving document (batch insert, insert validation)
• Removing document
• Updating document (document replacement, using modifiers, up inserts, updating
multipledocuments, returning updated documents)
• Execute at least 10 queries on any suitable MongoDB database that demonstrates
following:
a. Find and find One (specific values)
b. Query criteria (Query conditionals, OR queries, $not, Conditional semantics) Type-
specific queries (Null, Regular expression, Querying
arrays)
c. $ where queries
d. Cursors (Limit, skip, sort, advanced query options)

Creating Database and Collection in MongoDB

1. Create Database
In MongoDB, you do not need to explicitly create a database. MongoDB will create the
database when you first store data in that database. Use the following command to switch to
a new or existing database:

use StudentDB;

This switches to 'StudentDB'. If it doesn’t exist, MongoDB will create it when a document is
inserted.

2. Create Collection
Collections are like tables in RDBMS. Collections are created automatically when you insert
a document, but you can also create them explicitly using the following command:

db.createCollection("students");

This command explicitly creates a collection named 'students'.

3. Example: Insert Data to Create Collection and Database


You can insert a document directly to create both the database and collection if they don’t
exist:
db.students.insertOne({
name: "Rahul Sharma",
age: 21,
department: "Computer",
marks: [85, 78, 90],
email: "[email protected]"
});

After this command, 'StudentDB' and 'students' collection will be created (if not already
existing).

📘 Insert and Save Documents in MongoDB

In MongoDB, documents are inserted into collections using the insertOne() or


insertMany() methods. These methods are used to add and save data to your database.

🧩 1. insertOne() – Insert a Single Document

✅ Syntax:
js
CopyEdit
db.collection.insertOne({ document });

🧪 Example:
js
CopyEdit
db.students.insertOne({
name: "Rahul Sharma",
age: 21,
department: "Computer",
marks: [85, 78, 90],
email: "[email protected]"
});

This creates a new document in the students collection.


MongoDB automatically adds a unique _id field to each document if not provided.

🧩 2. insertMany() – Batch Insert Multiple Documents

✅ Syntax:
js
CopyEdit
db.collection.insertMany([{ doc1 }, { doc2 }, ...]);

🧪 Example:
js
CopyEdit
db.students.insertMany([
{
name: "Priya Desai",
age: 22,
department: "IT",
marks: [80, 82, 88],
email: "[email protected]"
},
{
name: "Amit Patil",
age: 23,
department: "Mechanical",
marks: [75, 70, 65],
email: "[email protected]"
}
]);

This adds two documents to the students collection in a single operation.

Remove Documents in MongoDB

MongoDB provides two main methods to remove documents from a collection:

 deleteOne() – removes one matching document.


 deleteMany() – removes all matching documents.

✅ 1. deleteOne() – Remove a Single Document

📌 Syntax:
js
CopyEdit
db.collection.deleteOne({ filter });

🧪 Example:
js
CopyEdit
db.students.deleteOne({ name: "Rahul Sharma" });

This deletes the first document where name is "Rahul Sharma".


✅ 2. deleteMany() – Remove Multiple Documents

📌 Syntax:
js
CopyEdit
db.collection.deleteMany({ filter });

🧪 Example:
js
CopyEdit
db.students.deleteMany({ department: "Mechanical" });

This removes all documents where department is "Mechanical".

🛑 3. Caution: Remove All Documents

If you pass an empty filter {}, all documents in the collection will be deleted.

⚠️Example:
js
CopyEdit
db.students.deleteMany({});

This deletes every document in the students collection. Use with caution!

🔍 Check Deleted Count

Both methods return a result with a deletedCount field that tells you how many
documents were deleted.

$set Modifier
Meaning:

$set is used to assign a new value to a field in a document without replacing the entire
document.

Syntax:

db.collection.updateOne(
{ _id: 1 },
{ $set: { field: value } }
)

Example:

db.students.updateOne(
{ name: "Rahul Sharma" },
{ $set: { department: "AI & DS" } }
);

This changes only the 'department' field for Rahul, keeping other fields unchanged.

Update Documents in MongoDB

MongoDB provides several ways to update documents. You can:

 Replace the entire document.


 Modify specific fields using update operators/modifiers like $set, $inc, $push,
etc.
 Use updateOne(), updateMany(), or replaceOne() depending on your use case.

✅ 1. updateOne() – Update a Single Document

📌 Syntax:
js
CopyEdit
db.collection.updateOne(
{ filter },
{ update_operator }
);

$inc Modifier
Meaning:

$inc is used to increment or decrement the value of a numeric field.

Syntax:

db.collection.updateOne(
{ _id: 1 },
{ $inc: { field: number } }
)

Example:

db.students.updateOne(
{ name: "Rahul Sharma" },
{ $inc: { age: 1 } }
);

This increases Rahul’s age by 1. To decrease, use a negative value (e.g., -1).

Common Update Operators:


Operator Description Example

$set Set or update a field { $set: { age: 22 } }

$inc Increment or decrement a number { $inc: { age: 1 } }

$push Add an item to an array { $push: { marks: 88 } }

$unset Remove a field from the document { $unset: { semester: "" } }

1. updateOne() – Update a Single Document

📌 Syntax:
js
CopyEdit
db.collection.updateOne(
{ filter },
{ update_operator }
);

🧪 Example using $set:


js
CopyEdit
db.students.updateOne(
{ name: "Rahul Sharma" },
{ $set: { department: "AI & DS" } }
);

Updates the department field of the first student named Rahul Sharma.
✅ 2. updateMany() – Update Multiple Documents

🧪 Example:
js
CopyEdit
db.students.updateMany(
{ department: "Computer" },
{ $set: { semester: "Sem-5" } }
);

Updates the semester field for all students in the Computer department.

✅ 3. replaceOne() – Replace Entire Document

📌 Syntax:
js
CopyEdit
db.collection.replaceOne(
{ filter },
{ new_document }
);

🧪 Example:
js
CopyEdit
db.students.replaceOne(
{ name: "Rahul Sharma" },
{
name: "Rahul Sharma",
age: 22,
department: "AI & DS",
marks: [90, 92, 95],
email: "[email protected]"
}
);

This replaces the entire document, so fields not included will be lost.

✅ 4. Upsert – Insert if Not Found

📌 Syntax:
js
CopyEdit
db.collection.updateOne(
{ filter },
{ update_operator },
{ upsert: true }
);
🧪 Example:
js
CopyEdit
db.students.updateOne(
{ name: "Neha Kulkarni" },
{ $set: { age: 20, department: "IT" } },
{ upsert: true }
);

If no matching document is found, it inserts a new one.

MongoDB Practical: Student Management System

1. Create Database & Collection

use studentDB
db.createCollection("students")

2. Insert & Save Documents


🔹 Single Insert

db.students.insertOne({
roll_no: 101,
name: "Ananya Sharma",
age: 20,
department: "Computer",
subjects: ["Math", "DS", "OS"],
cgpa: 8.7
})

🔹 Batch Insert

db.students.insertMany([
{
roll_no: 102,
name: "Ravi Patel",
age: 21,
department: "Mechanical",
subjects: ["Thermo", "Design"],
cgpa: 7.5
},
{
roll_no: 103,
name: "Neha Jain",
age: 19,
department: "Computer",
subjects: ["DS", "AI", "DBMS"],
cgpa: 9.0
}

{
roll_no: 104,
name: "Amol Godse",
age: 19,
department: "Computer",
subjects: ["DS", "AI", "DBMS"],
cgpa: 9.0
}

])

3. Remove Document
🔹 Delete One

db.students.deleteOne({ roll_no: 102 })

🔹 Delete Many

db.students.deleteMany({ department: "Mechanical" })

4. Update Document
🔹 Replace Document

db.students.replaceOne(
{ roll_no: 101 },
{
roll_no: 101,
name: "Ananya Sharma",
age: 21,
department: "Computer",
subjects: ["Math", "DSA", "OS"],
cgpa: 9.1
}
)

🔹 Using Modifiers ($set, $inc)

Modifier Purpose Example


$set Set/update the value of a field { $set: { name: "Anjali" } }
$inc Increment/decrement numeric field { $inc: { age: 2 } }

db.students.updateOne(
{ roll_no: 103 },
{ $set: { cgpa: 9.3 }, $inc: { age: 1 } }
)

🔹 Upsert

db.students.updateOne(
{ roll_no: 104 },
{
$set: {
name: "Amit Verma",
age: 22,
department: "Civil",
subjects: ["Structures"],
cgpa: 7.8
}
},
{ upsert: true }
)

🔹 Update Multiple Documents


db.students.updateMany(
{ department: "Computer" },
{ $set: { project: "AI Based Chatbot" } }
)

🔹 Return Updated Document

db.students.findAndModify({
query: { roll_no: 103 },
update: { $set: { cgpa: 9.5 } },
new: true
})

5. Execute 10 Queries
1 Find All
1. 1️⃣

db.students.find()

2. 2️⃣Find One

db.students.findOne({ roll_no: 103 })

3. 3️⃣CGPA > 8

db.students.find({ cgpa: { $gt: 8 } })

4. 4️⃣OR Query

db.students.find({ $or: [ { department: "Computer" }, { cgpa: { $lt: 8 } } ] })

5. 5️⃣NOT Query

db.students.find({ department: { $not: { $eq: "Computer" } } })

6. 6️⃣Null Check

db.students.find({ project: null })

7. 7️⃣Regex Query

db.students.find({ name: /^A/ })

8. 8️⃣Array Query
db.students.find({ subjects: "AI" })

9. 9️⃣$where Query

db.students.find({ $where: "this.cgpa > 9" })

10. 🔟 Cursor Options

db.students.find().sort({ cgpa: -1 }).skip(1).limit(2)

You might also like