Unit 4 Notes
Unit 4 Notes
🔹 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
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
# 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
class Rectangle:
def __init__(self, length: int, width: int):
self.length = length
self.width = width
# Test Case
r = Rectangle(10, 5)
print(r.get_area()) # Output: 50
🔹 3. Inheritance
class Employee:
def __init__(self, name: str, salary: int):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name: str, salary: int, team_size: int):
super().__init__(name, salary)
self.team_size = team_size
# Test Case
m = Manager("John", 50000, 10)
print(m.get_info()) # Output: Name: John, Salary: 50000, Team Size: 10
🔹 4. Abstraction
class Shape(ABC):
@abstractmethod
def area(self) -> float:
pass
class Circle(Shape):
def __init__(self, radius: float):
self.radius = radius
# Test Case
c = Circle(7)
print(round(c.area(), 2)) # Output: 153.94
🔹 5. Polymorphism
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
class SecureAccount:
def __init__(self):
self.__balance = 0 # Private variable
# Test Case
s = SecureAccount()
s.deposit(1000)
print(s.get_balance()) # Output: 1000
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:
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 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:
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"
Testcase:
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})"
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:
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)
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:
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 = []
A. Install MongoDB
client = MongoClient("mongodb://localhost:27017/")
db = client["school"] # creates 'school' database
collection = db["students"] # creates 'students' collection
🔹 C: Create (Insert)
🔹 R: Read (Query)
collection.find_one({"name": "Alice"})
collection.find({"age": {"$gt": 20}})
🔹 U: Update
🔹 D: Delete
collection.delete_one({"name": "Bob"})
collection.delete_many({"grade": "F"})
client = MongoClient("mongodb://localhost:27017/")
db = client["school"]
collection = db["students"]
🔹 CREATE (Insert)
collection.insert_many([
{"name": "Karan", "age": 20, "grade": "B"},
{"name": "Deepa", "age": 21, "grade": "C"}
])
🔹 READ (Query)
print(collection.find_one({"name": "Anu"}))
🔹 UPDATE
5. Rename a field
🔹 DELETE
collection.delete_one({"name": "Hari"})
collection.delete_many({})
collection.delete_many({"final_grade": "F"})
5. Conditional delete
To verify:
mongo
> show dbs
> use school
> db.students.find().pretty()
Examples:
Q1.
A new student "John" aged 20 joined the "Physics" department. Insert this student record into the
students collection.
Show the inserted document.
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.
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.
Output:
Document with nested marks object.
Q6.
db.students.findOne({name: "John"})
Output:
Document of John with fields.
Q7.
Output:
Cursor with all students older than 20.
Q8.
db.students.find({hobbies: "football"})
Output:
List of students with football in hobbies array.
Q9.
Output:
Cursor with students joined after specified date.
Q10.
Output:
List of students with math >= 80.
3. Update Questions
Q11.
Output:
MatchedCount: 1, ModifiedCount: 1
Q12.
Output:
Acknowledgment of one document updated.
Q13.
Output:
ModifiedCount equals total number of documents.
Q14.
Output:
Acknowledgment of update success.
Q15.
Output:
One document modified confirmation.
4. Delete Questions
Q16.
db.students.deleteOne({name: "Charlie"})
Output:
DeletedCount: 1
Q17.
db.students.deleteMany({status: "inactive"})
Output:
DeletedCount equals number of inactive students.
Q18.
Output:
Number of documents deleted.
Q19.
db.students.deleteOne({hobbies: "football"})
Output:
DeletedCount: 1
Q20.
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
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
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
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
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
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
Sample Output 7
[
{...}, {...}, {...}, {...}, {...}
]
Question 8
Write a MongoDB query to find the restaurants who achieved a score more than 90.
Answer 8
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
Sample Output 9
[
{...},
{...}
]
Question 10
Write a MongoDB query to find the restaurants which locate in latitude value less than -
95.754168.
Answer 10
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
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
Question 27
Write a MongoDB query to delete all restaurants that have a score less than 10.
Answer 27
Sample Output 27
Question 28
Write a MongoDB query to delete one restaurant document with the name "Central Perk Coffee
House".
Answer 28
Sample Output 28
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
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
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
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
Sample Output 35
Each will include basic MongoDB collections design, example documents, and example queries
to perform CRUD operations.
Collections:
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"
}
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")
});
db.registrations.insertOne({
event_id: ObjectId("64abf2c7b8a9c12a3e123456"),
user_id: ObjectId("64abf5d6b8a9c12a3e987654"),
registration_date: new Date(),
status: "confirmed"
});
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" } }
);
Collections:
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"
}
db.properties.find({
location: "Downtown, NY",
type: "rent",
status: "available"
});
db.properties.updateOne(
{ _id: ObjectId("64abf7b5b8a9c12a3e543210") },
{ $set: { status: "sold" } }
);
db.transactions.insertOne({
property_id: ObjectId("64abf7b5b8a9c12a3e543210"),
client_id: ObjectId("64abf8d1b8a9c12a3e456789"),
agent_id: ObjectId("64abf6e3b8a9c12a3e678901"),
transaction_date: new Date(),
price: 345000,
type: "sale"
});