0% found this document useful (0 votes)
8 views41 pages

Unit 4 Notes

The document covers Object-Oriented Programming (OOP) concepts such as objects, classes, constructors, inheritance, abstraction, polymorphism, and encapsulation, along with practical examples. It also discusses MongoDB setup, CRUD operations, and Python connectivity, providing illustrative programs for event management and real estate management. Additionally, it includes scenario-based questions to reinforce understanding of OOP principles and MongoDB functionalities.

Uploaded by

ithachiuchiya20
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)
8 views41 pages

Unit 4 Notes

The document covers Object-Oriented Programming (OOP) concepts such as objects, classes, constructors, inheritance, abstraction, polymorphism, and encapsulation, along with practical examples. It also discusses MongoDB setup, CRUD operations, and Python connectivity, providing illustrative programs for event management and real estate management. Additionally, it includes scenario-based questions to reinforce understanding of OOP principles and MongoDB functionalities.

Uploaded by

ithachiuchiya20
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/ 41

Unit-IV: OOP and Databases

Object, class, constructor, inheritance, abstraction, polymorphism, encapsulation;


MongoDB: Environmental Setup, creating new Database, CRUD Operations, Python DB
connectivity
Illustrative Programs: Event management using MongoDB, Real Estate management
using MongoDB

Object, class, constructor, inheritance, abstraction, polymorphism, encapsulation

🔹 1. Object
 An object is an instance of a class.
 It contains attributes (data) and methods (functions).
Example:
class Car {
public:
string brand;
void start() { cout << "Car started"; }
};
Car c1; // 'c1' is an object

🔹 2. Class
 A class is a blueprint/template for creating objects.
 It defines variables and methods common to all objects of that class.
Example:
class Student {
public:
string name;
int age;
void display() { cout << name << " " << age; }
};

🔹 3. Constructor
 A constructor is a special method that is called when an object is created.
 It has the same name as the class and no return type.
 Used to initialize objects.
Types: Default, Parameterized, Copy Constructor.
Example:
class Book {
public:
string title;
Book(string t) { title = t; }
};

🔹 4. Inheritance
 Inheritance allows one class to acquire the properties of another.
 Promotes code reuse.
 Types: Single, Multiple, Multilevel, Hierarchical, Hybrid.
Syntax:
class Parent {
public:
void show() { cout << "Parent"; }
};
class Child : public Parent { };

🔹 5. Abstraction
 Hiding internal details and showing only necessary features.
 Achieved using abstract classes or interfaces.
 Simplifies complex systems by modeling classes appropriate to the problem.
Example (in Java-like syntax):
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() { System.out.println("Circle"); }
}

🔹 6. Polymorphism
 Same interface, different behavior.
Types:
 Compile-time (Static): Function overloading, operator overloading.
 Run-time (Dynamic): Method overriding using virtual functions.
Example:
class Animal {
public: void sound() { cout << "Generic sound"; }
};
class Dog : public Animal {
public: void sound() { cout << "Bark"; }
};

🔹 7. Encapsulation
Binding data and methods that operate on that data into a single unit (class).
Protects data from outside interference (using private/protected access modifiers).
Promotes data hiding.
Example:
class Account {
private:
int balance;
public:
void setBalance(int b) { balance = b; }
int getBalance() { return balance; }
};

Summary Table
Concept Key Idea Feature
Object Instance of a class Real-world entity
Class Blueprint for objects Data + functions
Constructor Initializes object Auto-invoked
Inheritance Acquires parent properties Code reuse
Abstraction Hide details, show essentials Simplify
Polymorphism Many forms Flexibility
Encapsulation Data hiding Security

Example Programs

🔹 1. Object and Class

Problem: Bank Account Manager

class BankAccount:
def __init__(self, account_number: str, holder_name: str, balance: float):
self.account_number = account_number
self.holder_name = holder_name
self.balance = balance

def deposit(self, amount: float) -> None:


if amount > 0:
self.balance += amount
print(f"Deposited {amount}, new balance: {self.balance}")

def withdraw(self, amount: float) -> None:


if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}, new balance: {self.balance}")
else:
print("Insufficient balance or invalid amount!")

def display_balance(self) -> float:


return self.balance

# Test Case
acc = BankAccount("12345", "Alice", 1000.0)
acc.deposit(500.0)
acc.withdraw(200.0)
print(acc.display_balance()) # Output: 1300.0

🔹 2. Constructor

Problem: Rectangle Area

class Rectangle:
def __init__(self, length: int, width: int):
self.length = length
self.width = width

def get_area(self) -> int:


return self.length * self.width

# Test Case
r = Rectangle(10, 5)
print(r.get_area()) # Output: 50

🔹 3. Inheritance

Problem: Employee and Manager

class Employee:
def __init__(self, name: str, salary: int):
self.name = name
self.salary = salary

def get_info(self) -> str:


return f"Name: {self.name}, Salary: {self.salary}"

class Manager(Employee):
def __init__(self, name: str, salary: int, team_size: int):
super().__init__(name, salary)
self.team_size = team_size

def get_info(self) -> str:


return f"Name: {self.name}, Salary: {self.salary}, Team Size: {self.team_size}"

# Test Case
m = Manager("John", 50000, 10)
print(m.get_info()) # Output: Name: John, Salary: 50000, Team Size: 10

🔹 4. Abstraction

Problem: Abstract Class Shape and Circle

from abc import ABC, abstractmethod


import math

class Shape(ABC):
@abstractmethod
def area(self) -> float:
pass

class Circle(Shape):
def __init__(self, radius: float):
self.radius = radius

def area(self) -> float:


return math.pi * self.radius * self.radius

# Test Case
c = Circle(7)
print(round(c.area(), 2)) # Output: 153.94

🔹 5. Polymorphism

Problem: Animal Sounds

class Animal:
def make_sound(self) -> str:
return "Some sound"
class Dog(Animal):
def make_sound(self) -> str:
return "Bark"

class Cat(Animal):
def make_sound(self) -> str:
return "Meow"

# Test Case
animals = [Dog(), Cat(), Animal()]
for a in animals:
print(a.make_sound())
# Output:
# Bark
# Meow
# Some sound

🔹 6. Encapsulation

Problem: Secure Account

class SecureAccount:
def __init__(self):
self.__balance = 0 # Private variable

def deposit(self, amount: int):


if amount > 0:
self.__balance += amount
print(f"Deposited: {amount}")

def get_balance(self) -> int:


return self.__balance

# Test Case
s = SecureAccount()
s.deposit(1000)
print(s.get_balance()) # Output: 1000

Scenario Based questions:


🔹 1. Object & Class: Bookstore Inventory

Scenario:
Design a Book class with title, author, price, and stock.
Add methods to apply discount, sell books, and restock.
Prevent selling if stock is insufficient.
Return remaining stock and total sale after each transaction.

Testcase:

b = Book("AI Mastery", "Dr. Ada", 300, 10)


b.apply_discount(10)
b.sell(3)
b.restock(5)
print(b.get_stock(), b.get_total_sales())

Output: 12 810.0

Solution:

class Book:
def __init__(self, title, author, price, stock):
self.title = title
self.author = author
self.price = price
self.stock = stock
self.total_sales = 0.0

def apply_discount(self, discount):


self.price = round(self.price * (1 - discount / 100), 2)

def sell(self, quantity):


if quantity <= self.stock:
self.stock -= quantity
self.total_sales += quantity * self.price

def restock(self, quantity):


self.stock += quantity

def get_stock(self):
return self.stock

def get_total_sales(self):
return self.total_sales
🔹 2. Constructor: Student GPA System

Scenario:
Create a Student class with name, list of grades, and optional year.
Calculate GPA and categorize student as "Excellent", "Average", or "Fail".
If year not provided, default to 1.
Support adding new grades later.

Testcase:

s = Student("Alice", [85, 90, 78])


print(s.gpa(), s.status())
s.add_grade(92)
print(s.gpa(), s.status())

Output:
84.33 Excellent
86.25 Excellent

Solution:

class Student:
def __init__(self, name, grades, year=1):
self.name = name
self.grades = grades
self.year = year

def gpa(self):
return round(sum(self.grades) / len(self.grades), 2)

def status(self):
avg = self.gpa()
if avg >= 85:
return "Excellent"
elif avg >= 50:
return "Average"
else:
return "Fail"

def add_grade(self, mark):


self.grades.append(mark)

🔹 3. Inheritance: Online Store


Scenario:
Create base class Product with price and name.
Derived class DigitalProduct adds download_size and license_key.
Include method to return details and price with tax.
Use inheritance and method overriding.

Testcase:

p = DigitalProduct("Photoshop", 250, "500MB", "ABC123")


print(p.details())

Output:
Photoshop - $275.0 (500MB, Key: ABC123)

Solution:

class Product:
def __init__(self, name, price):
self.name = name
self.price = price

def get_price_with_tax(self):
return round(self.price * 1.1, 2)

class DigitalProduct(Product):
def __init__(self, name, price, size, key):
super().__init__(name, price)
self.size = size
self.key = key

def details(self):
return f"{self.name} - ${self.get_price_with_tax()} ({self.size}, Key: {self.key})"

🔹 4. Abstraction: Shape Area Calculator

Scenario:
Create an abstract class Shape with method area() and perimeter().
Create Rectangle and Circle subclasses.
Include validation for dimensions.
Return values rounded to 2 decimal places.

Testcase:

r = Rectangle(10, 5)
c = Circle(7)
print(r.area(), r.perimeter())
print(c.area(), c.perimeter())

Output:
50 30
153.94 43.98

Solution:

from abc import ABC, abstractmethod


import math

class Shape(ABC):
@abstractmethod
def area(self): pass

@abstractmethod
def perimeter(self): pass

class Rectangle(Shape):
def __init__(self, l, w):
self.l = l
self.w = w

def area(self):
return self.l * self.w

def perimeter(self):
return 2 * (self.l + self.w)

class Circle(Shape):
def __init__(self, r):
self.r = r

def area(self):
return round(math.pi * self.r ** 2, 2)

def perimeter(self):
return round(2 * math.pi * self.r, 2)

🔹 5. Polymorphism: Payment Gateway

Scenario:
Create base class PaymentMethod with method pay(amount).
Create CreditCard, UPI, and Wallet subclasses with different fees.
Use same interface to pay with different types.
Return final amount after applying fees.

Testcase:

methods = [CreditCard(), UPI(), Wallet()]


for m in methods:
print(m.pay(1000))

Output:
1030.0
1000.0
1015.0

Solution:

class PaymentMethod:
def pay(self, amount):
return amount

class CreditCard(PaymentMethod):
def pay(self, amount):
return round(amount * 1.03, 2)

class UPI(PaymentMethod):
def pay(self, amount):
return amount

class Wallet(PaymentMethod):
def pay(self, amount):
return round(amount * 1.015, 2)

🔹 6. Encapsulation: SecureBankAccount

Scenario:
Create BankAccount with private balance and PIN.
Support deposit, withdrawal, and balance check with correct PIN.
Disallow access without PIN.
Log all transactions for audit.

Testcase:

acc = BankAccount(1234)
acc.deposit(1000, 1234)
acc.withdraw(300, 1234)
print(acc.get_balance(1234))
print(acc.transaction_log)

Output:
700
['Deposited 1000', 'Withdrew 300']

Solution:

class BankAccount:
def __init__(self, pin):
self.__balance = 0
self.__pin = pin
self.transaction_log = []

def deposit(self, amount, pin):


if pin == self.__pin:
self.__balance += amount
self.transaction_log.append(f"Deposited {amount}")

def withdraw(self, amount, pin):


if pin == self.__pin and self.__balance >= amount:
self.__balance -= amount
self.transaction_log.append(f"Withdrew {amount}")

def get_balance(self, pin):


return self.__balance if pin == self.__pin else "Access Denied"

MongoDB: Environmental Setup, creating new Database, CRUD Operations, Python DB


connectivity
 ✅ Environmental Setup
 ✅ Creating a New Database
 ✅ CRUD Operations (Create, Read, Update, Delete)
 ✅ Python MongoDB Connectivity using pymongo

🔧 1. MongoDB: Environmental Setup

A. Install MongoDB

1. Download from: https://www.mongodb.com/try/download/community


2. Install and run MongoDB as a service (default port: 27017)
3. Use MongoDB Compass (GUI) or mongo shell (CLI) for access

B. Install pymongo (Python MongoDB Driver)

pip install pymongo

📂 2. Creating a New Database

MongoDB creates a database when you insert the first document.

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["school"] # creates 'school' database
collection = db["students"] # creates 'students' collection

🛠 3. CRUD Operations – Full Explanation

MongoDB is document-based. Each record is a JSON-like object (BSON internally).

🔹 C: Create (Insert)

collection.insert_one({"name": "John", "age": 20, "grade": "A"})


collection.insert_many([
{"name": "Alice", "age": 22, "grade": "B"},
{"name": "Bob", "age": 21, "grade": "C"}
])

🔹 R: Read (Query)

collection.find_one({"name": "Alice"})
collection.find({"age": {"$gt": 20}})

🔹 U: Update

collection.update_one({"name": "John"}, {"$set": {"grade": "A+"}})


collection.update_many({"grade": "C"}, {"$set": {"status": "needs improvement"}})

🔹 D: Delete

collection.delete_one({"name": "Bob"})
collection.delete_many({"grade": "F"})

🔌 4. Python MongoDB Connectivity: Basic Template

from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["school"]
collection = db["students"]

✅ 5 Examples for Each CRUD Operation with Output

🔹 CREATE (Insert)

1. Insert one student

collection.insert_one({"name": "Anu", "age": 19, "grade": "A"})

2. Insert multiple students

collection.insert_many([
{"name": "Karan", "age": 20, "grade": "B"},
{"name": "Deepa", "age": 21, "grade": "C"}
])

3. Insert with nested documents

collection.insert_one({"name": "Ravi", "age": 22, "marks": {"math": 88, "science": 91}})

4. Insert using dynamic data

student = {"name": "Sita", "age": 18, "grade": "A"}


collection.insert_one(student)

5. Insert with auto-generated _id

student = {"name": "Hari", "age": 23, "grade": "B"}


result = collection.insert_one(student)
print(result.inserted_id)

🔹 READ (Query)

1. Find one document

print(collection.find_one({"name": "Anu"}))

2. Find students older than 20

for student in collection.find({"age": {"$gt": 20}}):


print(student)

3. Find specific fields only

for student in collection.find({}, {"_id": 0, "name": 1, "grade": 1}):


print(student)

4. Find using $in operator

for student in collection.find({"grade": {"$in": ["A", "B"]}}):


print(student)

5. Find and sort by age

for student in collection.find().sort("age", 1):


print(student)

🔹 UPDATE

1. Update a single student's grade

collection.update_one({"name": "Deepa"}, {"$set": {"grade": "B+"}})

2. Update multiple students

collection.update_many({"grade": "B"}, {"$set": {"status": "good"}})


3. Increment age

collection.update_one({"name": "Ravi"}, {"$inc": {"age": 1}})

4. Add new field

collection.update_one({"name": "Sita"}, {"$set": {"sports": "basketball"}})

5. Rename a field

collection.update_many({}, {"$rename": {"grade": "final_grade"}})

🔹 DELETE

1. Delete one student

collection.delete_one({"name": "Hari"})

2. Delete students with age < 20

collection.delete_many({"age": {"$lt": 20}})

3. Delete all documents

collection.delete_many({})

4. Delete students with specific grade

collection.delete_many({"final_grade": "F"})

5. Conditional delete

collection.delete_many({"age": {"$gt": 30}, "final_grade": "C"})

🧪 Testing Environment Setup (Optional CLI)

To verify:

mongo
> show dbs
> use school
> db.students.find().pretty()
Examples:

1. Create (Insert) Questions

Q1.

A new student "John" aged 20 joined the "Physics" department. Insert this student record into the
students collection.
Show the inserted document.

db.students.insertOne({name: "John", age: 20, department: "Physics"})

Output:
Acknowledgment with insertedId of the new document.

Q2.

Insert three students in one query with names: "Alice", "Bob", and "Charlie". Each has an age
and department field.
Show how many documents were inserted.

db.students.insertMany([
{name: "Alice", age: 19, department: "Math"},
{name: "Bob", age: 21, department: "Chemistry"},
{name: "Charlie", age: 20, department: "Biology"}
])

Output:
InsertedCount: 3, InsertedIds: Array of new IDs.

Q3.

Add a new student "David" with hobbies as ["reading", "football"]. Insert into the students
collection.
Show the inserted student document.
db.students.insertOne({name: "David", hobbies: ["reading", "football"]})

Output:
Inserted document ID with array field hobbies.

Q4.

Insert a student "Emma" with join_date set to 2024-01-10.


Show the inserted document with date field.

db.students.insertOne({name: "Emma", join_date: ISODate("2024-01-10")})

Output:
Acknowledgment with insertedId and date stored.

Q5.

Insert a student "Fiona" with marks for math=85 and physics=90 stored as a sub-document.
Show the document structure after insertion.

db.students.insertOne({name: "Fiona", marks: {math: 85, physics: 90}})

Output:
Document with nested marks object.

2. Read (Query) Questions

Q6.

Find student with name "John" in students collection.


Show the matching student document.

db.students.findOne({name: "John"})

Output:
Document of John with fields.
Q7.

Find all students aged above 20.


List of student documents matching criteria.

db.students.find({age: {$gt: 20}})

Output:
Cursor with all students older than 20.

Q8.

Find students having "football" as a hobby.


Show all matching documents.

db.students.find({hobbies: "football"})

Output:
List of students with football in hobbies array.

Q9.

Find students who joined after 2023-12-31.


Show all matched students.

db.students.find({join_date: {$gt: ISODate("2023-12-31")}})

Output:
Cursor with students joined after specified date.

Q10.

Find students with math marks greater or equal to 80.


Show matched student documents.

db.students.find({"marks.math": {$gte: 80}})

Output:
List of students with math >= 80.
3. Update Questions

Q11.

Update "John" student’s department to "Astronomy".


Show update acknowledgment.

db.students.updateOne({name: "John"}, {$set: {department: "Astronomy"}})

Output:
MatchedCount: 1, ModifiedCount: 1

Q12.

Increase age of "Alice" by 1 year.


Show update status.

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

Output:
Acknowledgment of one document updated.

Q13.

Add a new field "status":"active" to all students.


Show count of updated documents.

db.students.updateMany({}, {$set: {status: "active"}})

Output:
ModifiedCount equals total number of documents.

Q14.

Add a new hobby "coding" to "David"’s hobbies array.


Show update result.
db.students.updateOne({name: "David"}, {$push: {hobbies: "coding"}})

Output:
Acknowledgment of update success.

Q15.

Remove the "physics" marks field from "Fiona".


Show update status.

db.students.updateOne({name: "Fiona"}, {$unset: {"marks.physics": ""}})

Output:
One document modified confirmation.

4. Delete Questions

Q16.

Delete student with name "Charlie".


Show delete acknowledgment.

db.students.deleteOne({name: "Charlie"})

Output:
DeletedCount: 1

Q17.

Delete all students with status "inactive".


Show count of deleted documents.

db.students.deleteMany({status: "inactive"})

Output:
DeletedCount equals number of inactive students.
Q18.

Delete students aged below 18.


Show delete confirmation.

db.students.deleteMany({age: {$lt: 18}})

Output:
Number of documents deleted.

Q19.

Delete student with hobby "football".


Show delete result.

db.students.deleteOne({hobbies: "football"})

Output:
DeletedCount: 1

Q20.

Delete all documents in students collection (clear all).


Show delete acknowledgment.

db.students.deleteMany({})

Output:
DeletedCount equals total documents before deletion.
Question 1

Write a MongoDB query to display all the documents in the collection restaurants.

Answer 1

db.restaurants.find()

Sample Output 1

[
{
"_id": ObjectId("..."),
"restaurant_id": "40356453",
"name": "Central Perk Cafe",
"borough": "Manhattan",
"cuisine": "Cafe",
"address": { "building": "123", "street": "Main St", "zipcode": "10001" },
"grades": [{ "grade": "A", "score": 12, "date": ISODate("2023-03-01") }]
},
{...}
]

Question 2

Write a MongoDB query to display the fields restaurant_id, name, borough and cuisine for all
the documents in the collection restaurants.

Answer 2

db.restaurants.find({}, { restaurant_id: 1, name: 1, borough: 1, cuisine: 1 })

Sample Output 2

[
{
"restaurant_id": "40356453",
"name": "Central Perk Cafe",
"borough": "Manhattan",
"cuisine": "Cafe"
},
{...}
]
Question 3

Write a MongoDB query to display the fields restaurant_id, name, borough and cuisine, but
exclude the field _id for all the documents in the collection restaurants.

Answer 3

db.restaurants.find({}, { restaurant_id: 1, name: 1, borough: 1, cuisine: 1, _id: 0 })

Sample Output 3

[
{
"restaurant_id": "40356453",
"name": "Central Perk Cafe",
"borough": "Manhattan",
"cuisine": "Cafe"
},
{...}
]

Question 4

Write a MongoDB query to display the fields restaurant_id, name, borough and zip code, but
exclude the field _id for all the documents in the collection restaurants.

Answer 4

db.restaurants.find({}, { restaurant_id: 1, name: 1, borough: 1, "address.zipcode": 1, _id: 0 })

Sample Output 4

[
{
"restaurant_id": "40356453",
"name": "Central Perk Cafe",
"borough": "Manhattan",
"address": { "zipcode": "10001" }
},
{...}
]

Question 5
Write a MongoDB query to display all the restaurants which are in the borough Bronx.

Answer 5

db.restaurants.find({ borough: "Bronx" })

Sample Output 5

[
{ "name": "Bronx Diner", "borough": "Bronx", ... },
{...}
]

Question 6

Write a MongoDB query to display the first 5 restaurants which are in the borough Bronx.

Answer 6

db.restaurants.find({ borough: "Bronx" }).limit(5)

Sample Output 6

[
{...}, {...}, {...}, {...}, {...}
]

Question 7

Write a MongoDB query to display the next 5 restaurants after skipping first 5 which are in the
borough Bronx.

Answer 7

db.restaurants.find({ borough: "Bronx" }).skip(5).limit(5)

Sample Output 7

[
{...}, {...}, {...}, {...}, {...}
]

Question 8
Write a MongoDB query to find the restaurants who achieved a score more than 90.

Answer 8

db.restaurants.find({ "grades.score": { $gt: 90 } })

Sample Output 8

[
{
"name": "High Score Diner",
"grades": [{ "score": 95, "grade": "A", "date": ISODate("2023-01-01") }]
},
{...}
]

Question 9

Write a MongoDB query to find the restaurants that achieved a score more than 80 but less than
100.

Answer 9

db.restaurants.find({ "grades.score": { $gt: 80, $lt: 100 } })

Sample Output 9

[
{...},
{...}
]

Question 10

Write a MongoDB query to find the restaurants which locate in latitude value less than -
95.754168.

Answer 10

db.restaurants.find({ "address.coord.0": { $lt: -95.754168 } })

Sample Output 10

[
{...},
{...}
]

Question 11

Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American'
and their grade score more than 70 and latitude less than -65.754168.

Answer 11

db.restaurants.find({
cuisine: { $ne: "American" },
"grades.score": { $gt: 70 },
"address.coord.0": { $lt: -65.754168 }
})

Sample Output 11

[
{...},
{...}
]

Question 12

Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American'
and achieved a score more than 70 and located in the longitude less than -65.754168.
Note: Do this query without using $and operator.

Answer 12

db.restaurants.find({
cuisine: { $ne: "American" },
"grades.score": { $gt: 70 },
"address.coord.0": { $lt: -65.754168 }
})

Sample Output 12

[
{...},
{...}
]
Question 13

Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American'
and achieved a grade point 'A' and not belong to the borough Brooklyn. The document must be
displayed according to the cuisine in descending order.

Answer 13

db.restaurants.find({
cuisine: { $ne: "American" },
"grades.grade": "A",
borough: { $ne: "Brooklyn" }
}).sort({ cuisine: -1 })

Sample Output 13

[
{...},
{...}
]

Question 14

Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those
restaurants which contain 'Wil' as first three letters for its name.

Answer 14

db.restaurants.find(
{ name: { $regex: /^Wil/ } },
{ restaurant_id: 1, name: 1, borough: 1, cuisine: 1, _id: 0 }
)

Sample Output 14

[
{ "restaurant_id": "40356453", "name": "Wild Grill", "borough": "Queens", "cuisine": "Grill" },
{...}
]

Question 15
Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those
restaurants which contain 'ces' as last three letters for its name.

Answer 15

db.restaurants.find(
{ name: { $regex: /ces$/ } },
{ restaurant_id: 1, name: 1, borough: 1, cuisine: 1, _id: 0 }
)

Sample Output 15

[
{ "restaurant_id": "40356454", "name": "Spices", "borough": "Bronx", "cuisine": "Indian" },
{...}
]

Question 16

Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those
restaurants which contain 'Reg' as three letters somewhere in its name.

Answer 16

db.restaurants.find(
{ name: { $regex: /Reg/ } },
{ restaurant_id: 1, name: 1, borough: 1, cuisine: 1, _id: 0 }
)

Sample Output 16

[
{ "restaurant_id": "40356455", "name": "Regal Diner", "borough": "Brooklyn", "cuisine":
"American" },
{...}
]

Question 17

Write a MongoDB query to find the restaurants which belong to the borough Bronx and prepared
either American or Chinese dish.

Answer 17
db.restaurants.find({
borough: "Bronx",
cuisine: { $in: ["American", "Chinese"] }
})

Sample Output 17

[
{...},
{...}
]

Question 18

Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those
restaurants which belong to the borough Staten Island or Queens or Bronx.

Answer 18

db.restaurants.find(
{ borough: { $in: ["Staten Island", "Queens", "Bronx"] } },
{ restaurant_id: 1, name: 1, borough: 1, cuisine: 1, _id: 0 }
)

Sample Output 18

[
{ "restaurant_id": "40356456", "name": "Island Diner", "borough": "Staten Island", "cuisine":
"Seafood" },
{...}
]

Question 19

Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those
restaurants which are not belonging to the borough Staten Island or Queens or Bronx.

Answer 19
db.restaurants.find(
{ borough: { $nin: ["Staten Island", "Queens", "Bronx"] } },
{ restaurant_id: 1, name: 1, borough: 1, cuisine: 1, _id: 0 }
)

Sample Output 19

[
{ "restaurant_id": "40356457", "name": "Central Perk Cafe", "borough": "Manhattan",
"cuisine": "Cafe" },
{...}
]

Question 20

Write a MongoDB query to find the restaurants which achieved a score not between 10 and 100.

Answer 20

db.restaurants.find({
"grades.score": { $not: { $gte: 10, $lte: 100 } }
})

Sample Output 20

[
{...},
{...}
]

Question 21

Write a MongoDB query to find the restaurants which achieved a score not between 10 and 100.
(Use $or operator)

Answer 21

db.restaurants.find({
$or: [
{ "grades.score": { $lt: 10 } },
{ "grades.score": { $gt: 100 } }
]
})
Sample Output 21

[
{...},
{...}
]

Question 22

Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American'
and achieved a score more than 70 and located in the longitude less than -65.754168.
Note: Use $and operator.

Answer 22

db.restaurants.find({
$and: [
{ cuisine: { $ne: "American" } },
{ "grades.score": { $gt: 70 } },
{ "address.coord.0": { $lt: -65.754168 } }
]
})

Sample Output 22

[
{...},
{...}
]

Question 23

Write a MongoDB query to find the restaurants which achieved a grade of "A", have a score
greater than 80 and located in the borough Brooklyn.

Answer 23

db.restaurants.find({
borough: "Brooklyn",
"grades.grade": "A",
"grades.score": { $gt: 80 }
})

Sample Output 23
[
{...},
{...}
]

Question 24

Write a MongoDB query to find the restaurants which do not contain the borough Queens and
have a cuisine of either Chinese or American.

Answer 24

db.restaurants.find({
borough: { $ne: "Queens" },
cuisine: { $in: ["Chinese", "American"] }
})

Sample Output 24

[
{...},
{...}
]

Question 25

Write a MongoDB query to update the name of the restaurant from "Central Perk Cafe" to
"Central Perk Coffee House".

Answer 25

db.restaurants.updateOne(
{ name: "Central Perk Cafe" },
{ $set: { name: "Central Perk Coffee House" } }
)

Sample Output 25

{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }

Question 26
Write a MongoDB query to update all restaurants in the borough Bronx to have their cuisine
changed to "American".

Answer 26

db.restaurants.updateMany(
{ borough: "Bronx" },
{ $set: { cuisine: "American" } }
)

Sample Output 26

{ "acknowledged": true, "matchedCount": 20, "modifiedCount": 20 }

Question 27

Write a MongoDB query to delete all restaurants that have a score less than 10.

Answer 27

db.restaurants.deleteMany({ "grades.score": { $lt: 10 } })

Sample Output 27

{ "acknowledged": true, "deletedCount": 5 }

Question 28

Write a MongoDB query to delete one restaurant document with the name "Central Perk Coffee
House".

Answer 28

db.restaurants.deleteOne({ name: "Central Perk Coffee House" })

Sample Output 28

{ "acknowledged": true, "deletedCount": 1 }

Question 29

Write a MongoDB query to count the total number of restaurants in the collection.
Answer 29

db.restaurants.countDocuments()

Sample Output 29

1000

Question 30

Write a MongoDB query to count the number of restaurants in the borough Manhattan.

Answer 30

db.restaurants.countDocuments({ borough: "Manhattan" })

Sample Output 30

300

Question 31

Write a MongoDB query to find the average score of all restaurants in the borough Brooklyn.

Answer 31

db.restaurants.aggregate([
{ $match: { borough: "Brooklyn" } },
{ $unwind: "$grades" },
{ $group: { _id: null, avgScore: { $avg: "$grades.score" } } }
])

Sample Output 31

[{ "_id": null, "avgScore": 72.5 }]

Question 32

Write a MongoDB query to find the restaurant with the highest score.

Answer 32

db.restaurants.aggregate([
{ $unwind: "$grades" },
{ $sort: { "grades.score": -1 } },
{ $limit: 1 }
])

Sample Output 32

[
{
"_id": ObjectId("..."),
"name": "Best Diner",
"grades": [{ "score": 100, "grade": "A", "date": ISODate("2023-01-01") }]
}
]

Question 33

Write a MongoDB query to find the number of restaurants for each cuisine type.

Answer 33

db.restaurants.aggregate([
{ $group: { _id: "$cuisine", count: { $sum: 1 } } }
])

Sample Output 33

[
{ "_id": "American", "count": 300 },
{ "_id": "Chinese", "count": 200 },
{...}
]

Question 34

Write a MongoDB query to find all restaurants whose name starts with "Wil" and sort them by
name in ascending order.

Answer 34

db.restaurants.find({ name: { $regex: /^Wil/ } }).sort({ name: 1 })

Sample Output 34
[
{ "name": "Wild Grill", ... },
{ "name": "Willow Cafe", ... }
]

Question 35

Write a MongoDB query to add a new field named open with the value true to all restaurant
documents.

Answer 35

db.restaurants.updateMany({}, { $set: { open: true } })

Sample Output 35

{ "acknowledged": true, "matchedCount": 1000, "modifiedCount": 1000 }

Illustrative example programs for MongoDB-based


applications:
1. Event Management System
2. Real Estate Management System

Each will include basic MongoDB collections design, example documents, and example queries
to perform CRUD operations.

1. Event Management System Using MongoDB

Collections:

 events — stores event details


 users — stores user profiles (attendees, organizers)
 registrations — stores user registrations for events

Sample Documents:

events collection
{
"_id": ObjectId("64abf2c7b8a9c12a3e123456"),
"name": "Tech Conference 2025",
"location": "New York Convention Center",
"date": ISODate("2025-09-15T09:00:00Z"),
"category": "Technology",
"capacity": 500,
"organizer_id": ObjectId("64abf1f2b8a9c12a3e654321")
}

users collection

{
"_id": ObjectId("64abf1f2b8a9c12a3e654321"),
"name": "Alice Johnson",
"email": "[email protected]",
"role": "organizer" // or "attendee"
}

registrations collection

{
"_id": ObjectId("64abf3a5b8a9c12a3e789012"),
"event_id": ObjectId("64abf2c7b8a9c12a3e123456"),
"user_id": ObjectId("64abf5d6b8a9c12a3e987654"),
"registration_date": ISODate("2025-05-22T10:30:00Z"),
"status": "confirmed" // or "cancelled"
}

Example MongoDB operations:

1. Insert a new event

db.events.insertOne({
name: "AI Summit 2025",
location: "San Francisco",
date: new Date("2025-11-10T09:00:00Z"),
category: "Artificial Intelligence",
capacity: 300,
organizer_id: ObjectId("64abf1f2b8a9c12a3e654321")
});

2. Register a user for an event

db.registrations.insertOne({
event_id: ObjectId("64abf2c7b8a9c12a3e123456"),
user_id: ObjectId("64abf5d6b8a9c12a3e987654"),
registration_date: new Date(),
status: "confirmed"
});

3. Find all events organized by a specific user

db.events.find({ organizer_id: ObjectId("64abf1f2b8a9c12a3e654321") });

4. List attendees registered for a given event

db.registrations.aggregate([
{ $match: { event_id: ObjectId("64abf2c7b8a9c12a3e123456") } },
{ $lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "attendee_info"
}
},
{ $unwind: "$attendee_info" },
{ $project: { "attendee_info.name": 1, "attendee_info.email": 1, _id: 0 } }
]);

5. Cancel a registration

db.registrations.updateOne(
{ _id: ObjectId("64abf3a5b8a9c12a3e789012") },
{ $set: { status: "cancelled" } }
);

2. Real Estate Management Using MongoDB

Collections:

 properties — stores property listings


 agents — stores real estate agents
 clients — stores client details
 transactions — stores property sale/rental transactions

Sample Documents:

properties collection

{
"_id": ObjectId("64abf7b5b8a9c12a3e543210"),
"title": "Modern 2BHK Apartment",
"location": "Downtown, NY",
"price": 350000,
"type": "sale", // or "rent"
"agent_id": ObjectId("64abf6e3b8a9c12a3e678901"),
"features": ["balcony", "parking", "gym"],
"listed_date": ISODate("2025-05-10T00:00:00Z"),
"status": "available" // or "sold", "rented"
}

agents collection

{
"_id": ObjectId("64abf6e3b8a9c12a3e678901"),
"name": "John Doe",
"email": "[email protected]",
"phone": "123-456-7890"
}

clients collection

{
"_id": ObjectId("64abf8d1b8a9c12a3e456789"),
"name": "Emma Smith",
"email": "[email protected]",
"phone": "987-654-3210",
"interests": ["sale", "2BHK", "Downtown"]
}

transactions collection

{
"_id": ObjectId("64abf9a2b8a9c12a3e123789"),
"property_id": ObjectId("64abf7b5b8a9c12a3e543210"),
"client_id": ObjectId("64abf8d1b8a9c12a3e456789"),
"agent_id": ObjectId("64abf6e3b8a9c12a3e678901"),
"transaction_date": ISODate("2025-05-21T14:00:00Z"),
"price": 345000,
"type": "sale"
}

Example MongoDB operations:

1. Insert a new property listing


db.properties.insertOne({
title: "Cozy 1BHK Condo",
location: "Uptown, NY",
price: 1800,
type: "rent",
agent_id: ObjectId("64abf6e3b8a9c12a3e678901"),
features: ["pool", "gym"],
listed_date: new Date(),
status: "available"
});

2. Find all available properties for rent in "Downtown, NY"

db.properties.find({
location: "Downtown, NY",
type: "rent",
status: "available"
});

3. Update the status of a property to 'sold' after transaction

db.properties.updateOne(
{ _id: ObjectId("64abf7b5b8a9c12a3e543210") },
{ $set: { status: "sold" } }
);

4. Record a new transaction

db.transactions.insertOne({
property_id: ObjectId("64abf7b5b8a9c12a3e543210"),
client_id: ObjectId("64abf8d1b8a9c12a3e456789"),
agent_id: ObjectId("64abf6e3b8a9c12a3e678901"),
transaction_date: new Date(),
price: 345000,
type: "sale"
});

5. Find all properties managed by a particular agent

db.properties.find({ agent_id: ObjectId("64abf6e3b8a9c12a3e678901") });

You might also like